C++笔记-Qt中使用Lambda时[]中的形式
生活随笔
收集整理的這篇文章主要介紹了
C++笔记-Qt中使用Lambda时[]中的形式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有幾個地方要注意的:
[]這個表示Lambda的開始,如果要加參數可以這樣:[]()后面括號里面放參數,Qt中connect中的信號,參數
1. []:里面為空,表示不使用任何參數對象的參數;
2. =:表示按值的方式進行傳遞;
3. &:表示以引用的方式進行傳遞;
4. this:表示函數體內可以使用Lambda所在類中的成員變量;
5. a:按值的方式進行傳遞,默認是不能修改的,如果要修改,需要添加mutable修飾符。
?
程序結構如下:
如下代碼:
LambdaInQt.pro
QT -= guiCONFIG += c++11 console CONFIG -= app_bundle# The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp# Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += targetHEADERS += \Test.hTest.h
#ifndef TEST_H #define TEST_H#include <QObject> #include <QTimer> #include <QDebug>class Test1{public:Test1(){}Test1(const Test1 &test){this->m_a = test.m_a;}Test1 &operator = (const Test1 &test){this->m_a = test.m_a;}int m_a; };class Test2{public:int m_a; };class MyEmit : public QObject{Q_OBJECTpublic:MyEmit() : QObject(nullptr){QTimer::singleShot(1000, [this](){this->m_test1.m_a = 10;this->m_test2.m_a = 20;});Test1 tmpTest1;tmpTest1.m_a = 100;QTimer::singleShot(1000, [=](){this->m_a = 100;this->m_test1.m_a = 100;});QTimer::singleShot(1000, [&](){this->m_a = 100;tmpTest1.m_a = 300;});int tmpa = 100;QTimer::singleShot(1000, [tmpa](){qDebug() << tmpa;});QTimer::singleShot(1000, [tmpTest1](){qDebug() << tmpTest1.m_a;});}signals:void sendSomeThing();void sendToDoSomeThing();private:int m_a;int m_b;Test1 m_test1;Test2 m_test2; };#endif // TEST_Hmain.cpp
#include <QCoreApplication> #include <QDebug> #include <QTimer> #include "Test.h"int main(int argc, char *argv[]) {QCoreApplication a(argc, argv);MyEmit myEmit;QTimer::singleShot(3000, [&]{emit myEmit.sendSomeThing();});QEventLoop loop;QObject::connect(&myEmit, &MyEmit::sendSomeThing, [=](){});loop.exec();qDebug() << "over";return a.exec(); }?
?
總結
以上是生活随笔為你收集整理的C++笔记-Qt中使用Lambda时[]中的形式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DM工作笔记-查看会话(session)
- 下一篇: canvas笔记-画三角形并计算其外心(