C++笔记-Qt中使用Lambda时[]中的形式

有几个地方要注意的:

[]这个表示Lambda的开始,如果要加参数可以这样:[]()后面括号里面放参数,Qt中connect中的信号,参数

1. []:里面为空,表示不使用任何参数对象的参数;

2. =:表示按值的方式进行传递;

3. &:表示以引用的方式进行传递;

4. this:表示函数体内可以使用Lambda所在类中的成员变量;

5. a:按值的方式进行传递,默认是不能修改的,如果要修改,需要添加mutable修饰符。

 

程序结构如下:

如下代码:

LambdaInQt.pro

QT -= gui

CONFIG += 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.0

SOURCES += \
        main.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

HEADERS += \
    Test.h

Test.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_OBJECT

public:
    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_H

main.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();
}

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页