- Qt5 C++ GUI Programming Cookbook
- Lee Zhi Eng
- 261字
- 2021-07-02 12:17:58
How it works...
The preceding example is a very simple application that showcases the use of lambda expressions to connect a signal with a lambda function or a regular function without declaring any slot function, and thus does not need to be inherited from a QObject class. This is especially useful for calling asynchronous processes that are not under UI objects.
Lambda expressions are functions that get defined within another function anonymously, which is quite similar to the anonymous functions in JavaScript. The format of a lambda function looks like this:
[captured variables](arguments) {
lambda code
}
You can insert variables into a lambda expression by placing them into the captured variables part, like we did in the example project in this recipe. We capture the QNetworkReply object called reply, and the QString object called html, and put them in our lambda expression.
Then, we can use these variables within our lambda code, as shown in the following code:
[reply, html]() {
html->append(QString(reply->readAll()));
}
The argument part is similar to an ordinary function, where you input values to the arguments and use them within your lambda code. In this case, the values of bytesReceived and bytesTotal are coming from the downloadProgress signal:
QObject::connect(reply, &QNetworkReply::downloadProgress,
[reply](qint64 bytesReceived, qint64 bytesTotal) {
qDebug() << "Progress: " << bytesReceived << "bytes /" << bytesTotal << "bytes";
});
You can also capture all variables that are used in your function using the equals sign. In this case, we captured the html variable without specifying it in the captured variable area:
[=]() {
printHTML(*html);
}
- 動(dòng)態(tài)對(duì)比增強(qiáng)磁共振成像
- 口腔科常見(jiàn)及多發(fā)病就醫(yī)指南系列:口腔正畸就醫(yī)指南
- 超聲醫(yī)學(xué)專(zhuān)科能力建設(shè)專(zhuān)用初級(jí)教材:介入分冊(cè)
- 老年癡呆居家康復(fù)指導(dǎo)
- 孤獨(dú)癥譜系障礙兒童家庭訓(xùn)練100問(wèn)
- 新生兒聽(tīng)力篩查
- 常見(jiàn)惡性腫瘤治療原則與實(shí)施方案
- 癲癇綜合征管理手冊(cè)
- 急危重癥容量管理
- 實(shí)用皮膚鏡學(xué)
- 向陽(yáng)而生:柱子哥的抗癌指南
- 腫瘤標(biāo)志物
- 運(yùn)動(dòng)導(dǎo)致的骨骼肌細(xì)胞結(jié)構(gòu)損傷及其診斷
- 運(yùn)動(dòng)損傷圖解
- 骨科疾病的分類(lèi)與分型標(biāo)準(zhǔn)(第2版)