![Qt5 C++ GUI Programming Cookbook](https://wfqqreader-1252317822.image.myqcloud.com/cover/790/36698790/b_36698790.jpg)
上QQ阅读APP看书,第一时间看更新
How to do it...
To learn how to achieve asynchronous operations using the signals and slots mechanism, let's follow this example:
- Create a Qt Console Application project:
![](https://epubservercos.yuewen.com/B40C46/19470380801500706/epubprivate/OEBPS/Images/849ef28e-8e5a-4692-8638-edb29b347cff.png?sign=1738979956-9G7AfsZuhdWuaPqQ42i9n15bg2LfVc2Z-0-8b1774b6e7acd35b9b1caf31f9dcb10a)
- This type of project will only provide a main.cpp file for you, instead of mainwindow.h and mainwindow.cpp, like our previous example projects. Let's open up main.cpp and add the following headers to it:
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDebug>
- Then, add the following code to our main() function. We will be using the QNetworkAccessManager class to initiate a GET request to the following web URL:
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
QString *html = new QString;
qDebug() << "Start";
QNetworkAccessManager manager;
QNetworkRequest req(QUrl("http://www.dustyfeet.com"));
QNetworkReply* reply = manager.get(req);
Then, we use C++11's lambda expression to connect QNetworkReply signals to inline functions:
QObject::connect(reply, &QNetworkReply::readyRead,
[reply, html]() {
html->append(QString(reply->readAll()));
});
QObject::connect(reply, &QNetworkReply::downloadProgress,
[reply](qint64 bytesReceived, qint64 bytesTotal) {
qDebug() << "Progress: " << bytesReceived << "bytes /" << bytesTotal << "bytes";
});
We can also use a lambda expression with connect() to call a function that is not under a QObject class:
QObject::connect(reply, &QNetworkReply::finished,
[=]() {
printHTML(*html);
});
return a.exec();
}
- Lastly, we define the printHTML() function, as shown in the following code:
void printHTML(QString html) {
qDebug() << "Done";
qDebug() << html;
}
- If you build and run the program now, you will see that it's functional even without declaring any slot function. Lambda expressions make declaring a slot function optional, but this is only recommended if your code is really short:
![](https://epubservercos.yuewen.com/B40C46/19470380801500706/epubprivate/OEBPS/Images/179c9d5e-18ce-47bc-97fc-f298288519c4.png?sign=1738979956-YGmT6rRYy3Ia1YLRL0GE2oHgGDRsMpF3-0-48f87d5a756d1b52075e6e2d4b4c6979)