Hello, I’m Lao Wu.

Recently I played Qt again, and I want to share some basic knowledge about Qt with you.

I personally love Qt, and it’s a handy tool for my C++ hobbyist.

The best way to learn about Qt is to read the official manual and examples. Here is an example provided by the official Qt.

HTTP download widget:

Click to see a larger image

Source file:

`Makefile`
`httpwindow.cpp`
`main.cpp`
`httpwindow.h`
`http.pro`

Here’s a quick description of how to implement the gadget, Let’s Go.

Directory:

2. Resolve the URL and create an empty file. 3. Send HTTP request and receive HTTP data 4. Add progress bar 5. Open the file 'automatically after downloading

1. Realize the main interface

The main interface is based on QDialog and includes:

  • Three LineEdit;
  • 1 the CheckBox;
  • 1 Label;
  • 2 the Button;

The code is as follows:

`httpwindow.h` `class HttpWindow : public QDialog` `{` `... ` `}` `````` `httpwindow.cpp` `HttpWindow::HttpWindow(QWidget *parent)` `: QDialog(parent)` `... ` `{` `QFormLayout *formLayout = new QFormLayout; ` `formLayout->addRow(tr("&URL:"), urlLineEdit); ` `formLayout->addRow(tr("&Download directory:"), downloadDirectoryLineEdit); ` `formLayout->addRow(tr("Default &file:"), defaultFileLineEdit); ` `formLayout->addRow(launchCheckBox); ` `QVBoxLayout *mainLayout = new QVBoxLayout(this); ` `mainLayout->addLayout(formLayout); ` `mainLayout->addWidget(statusLabel); ` `QPushButton *quitButton = new QPushButton(tr("Quit")); ` `QWidget::close); ` `QDialogButtonBox *buttonBox = new QDialogButtonBox; ` `buttonBox->addButton(downloadButton, QDialogButtonBox::ActionRole); ` `buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole); ` `mainLayout->addWidget(buttonBox); ` ` `}

Use QFormLayout for the form layout of the three edit boxes, and then QVBoxLayout for the overall vertical layout.

The main. CPP:

`int main(int argc, char *argv[])` `{` `... ` `HttpWindow httpWin; ` `httpWin.show(); ` `... ` ` `}

Operation effect:

At this point, there is only the interface; the Download button has no actual function.

2. Parse the URL and create an empty file

When the user clicks the Downaload button, the URL entered by the user is parsed and a new file is opened to save the file to be downloaded.

The code is as follows:

1. Bind slots for the Download button

`connect(downloadButton, &QAbstractButton::clicked, this, &HttpWindow::downloadFile); ` ` `}

2. Parse the URL

Void HttpWindow::downloadFile() ' '{'' '// Get URL' const QString urlSpec = urllineEdit-> text().trimmed(); ` `const QUrl newUrl = QUrl::fromUserInput(urlSpec); QString fileName = newUrl.filename (); ` `QString downloadDirectory = QDir::cleanPath(downloadDirectoryLineEdit->text().trimmed()); ` `fileName.prepend(downloadDirectory + '/'); ` ` `}

The filename is extracted from the URL and spliced together with the download path to form a complete file path.

3. Create an empty file

`void HttpWindow::downloadFile()` `{` `... ` `if (QFile::exists(fileName)) {` `QFile::remove((fileName)); ` `}` `file = openFileForWrite(fileName); ` `... ` `}` `std::unique_ptr<QFile> HttpWindow::openFileForWrite(const QString &fileName)` `{` `std::unique_ptr<QFile> file(new QFile(fileName)); ` `file->open(QIODevice::WriteOnly); ` `return file; ` ` `}

Operation effect:

3. Send HTTP requests and receive HTTP data

= = = = = = = = = = = = = = = = = = = = = = = = = = = =

In Qt, you can use QNetworkAccessManager to send an HTTP request and QNetworkReply to store an HTTP Reply.

`class HttpWindow : public QDialog` `{` `private:` `... ` `QUrl url; ` `QNetworkAccessManager qnam; ` `QNetworkReply *reply; ` `}; `

When the user presses the Download key, send the HTTP request:

`void HttpWindow::startRequest(const QUrl &requestedUrl)` `{` `url = requestedUrl; ` `reply = qnam.get(QNetworkRequest(url)); ` `connect(reply, &QIODevice::readyRead, this, &HttpWindow::httpReadyRead); ` `connect(reply, &QNetworkReply::finished, this, &HttpWindow::httpFinished); ` `statusLabel->setText(tr("Downloading %1..." ).arg(url.toString())); ` ` `}

When data arrives, write it to the file:

`void HttpWindow::httpReadyRead()` `{` `if (file)` `file->write(reply->readAll()); ` ` `}

When the data transmission is completed, the user will be reminded that the download is completed:

`void HttpWindow::httpFinished()` `{` `QFileInfo fi; ` `if (file) {` `fi.setFile(file->fileName()); ` `file->close(); ` `file.reset(); ` `}` `statusLabel->setText(tr("Downloaded %1 bytes to %2\nin\n%3")` `.arg(fi.size()).arg(fi.fileName(), QDir::toNativeSeparators(fi.absolutePath()))); ` `downloadButton->setEnabled(true); ` ` `}

Operation effect:

4. Add a progress bar

= = = = = = = = = = = =

After sending the request, create a progress bar.

The percentage of the progress bar is bound to the HTTP Reply data:

`void HttpWindow::startRequest(const QUrl &requestedUrl)` `{` `... ` `ProgressDialog *progressDialog = new ProgressDialog(url, nullptr); ` `... ` `connect(reply, &QNetworkReply::downloadProgress, progressDialog, &ProgressDialog::networkReplyProgress); ` `... ` `progressDialog->show(); ` `} ` ` / / update the progress bar as a percentage of ` ` void ProgressDialog: : networkReplyProgress (qint64 bytesRead, qint64 totalBytes)` `{` `setMaximum(totalBytes); ` `setValue(bytesRead); ` ` `}

Operation effect:

5. Open the file automatically after downloading

= = = = = = = = = = = = = = = = = =

QDesktopServices is used to access common desktop services.

Many desktop environments offer a range of services that perform common tasks through applications. For example, open a Web page or PDF as a user application preference.

When the download is complete, if the user enables the Launch File option, open the download file:

`void HttpWindow::httpFinished()` `{` `... ` `if (launchCheckBox->isChecked()) {` `QDesktopServices::openUrl(QUrl::fromLocalFile(fi.absoluteFilePath())); ` `}` `downloadButton->setEnabled(true); ` ` `}

Operation effect:

At this point, the implementation of the HTTP download widget is complete.

Hey hey, will you learn?

Relevant reference

https://doc.qt.io/qt-5/qtnetw…

Think about technology, but also think about life

Learn how to live as much as you learn technology.

Recommended books:

Index Fund Investment Guide

The author bank screws, focusing on low valuation index fund investing, systematically explains the various index funds and effective strategies for investing in index funds.

Click to see a larger image

What can be gained?

  • Reviewed some of the basic knowledge about the fund fixed investment;

You and I each have one apple, so if we swap apples, we still have one apple. But when you and I each have an idea, and we exchange ideas, we both have two ideas.

Think the article is valuable to you, might as well look at + share.

Recommended reading:

Album | Linux driver development

Album | a little C every day

Album | Linux system programming