官术网_书友最值得收藏!

How to do it...

To learn how to achieve asynchronous operations using the signals and slots mechanism, let's follow this example:

  1. Create a Qt Console Application project:
  1. 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>
  1. 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);

  1. 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";
});
  1. 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();
}
  1. Lastly, we define the printHTML() function, as shown in the following code:
void printHTML(QString html) {
qDebug() << "Done";
qDebug() << html;
}
  1. 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:
主站蜘蛛池模板: 梅河口市| 绩溪县| 娄烦县| 章丘市| 拜泉县| 灵山县| 广元市| 亳州市| 玉树县| 永丰县| 云林县| 武城县| 大埔区| 唐河县| 牟定县| 星座| 澄城县| 濮阳市| 民勤县| 齐齐哈尔市| 博野县| 石首市| 桐梓县| 鄂伦春自治旗| 习水县| 大渡口区| 平定县| 乌兰察布市| 古蔺县| 子洲县| 镇宁| 蒙阴县| 昌江| 麻阳| 台北县| 关岭| 读书| 察雅县| 遂宁市| 东山县| 侯马市|