qt中常用lambda表达式

qt中lambda表达式

什么是lambda

个人理解:没有函数名的函数

qt中使用基础

备注:都是在qt5中做的使用,我的qt版本是qt5.11.3

pro文件中
config+=c++11

常见的lambda表达式使用(延时执行操作)

举例:通过信号槽将t和tmpImage两个参数传进lambda表达式中,从而实现延时删除文件
方法一:

    QString tmpImg ="~/Picture/xx.png"
    QTimer *t = new QTimer(this);
    t->setSingleShot(true);
    connect(t, &QTimer::timeout, this, [t, tmpImg] {
        QFile(tmpImg).remove();
        t->deleteLater();
    });
    t->start(1000);

方法二:更简单的lambda方法

    QString tmpImg ="~/Picture/xx.png"
    QTimer::singleShot(1000,[tmpImg]{
        QFile(tmpImg).remove();
    });

常见的lambda表达式使用(信号槽)

    //Qt不传递参数lambda
    connect(this,&lambdaTest::testSingal,this,[=]{
        qDebug()<<QString("test");
    });
    //Qt带传递参数lambda
    connect(this,&lambdaTest::testSingal,this,[=](QString path){
        qDebug()<<path;
    });
    //Qt5风格
    connect(this,&lambdaTest::testSingal,this,&lambdaTest::testSlot);
    //Qt4风格
    connect(this,SIGNAL(testSingal(QString)),this,SLOT(testSlot(QString)));
    
    QString path="test";
    emit testSingal(path);
    
    void lambdaTest::testSlot(QString path)
    {
        qDebug()<<path;
    }

如果要加上第五个参数,也是没有问题的

    //Qt不传递参数lambda
    connect(this,&lambdaTest::testSingal,this,[=]{
        qDebug()<<QString("test");
    },Qt::QueuedConnection);
    //Qt带传递参数lambda
    connect(this,&lambdaTest::testSingal,this,[=](QString path){
        qDebug()<<path;
    },Qt::QueuedConnection);
    //Qt5风格
    connect(this,&lambdaTest::testSingal,this,&lambdaTest::testSlot,Qt::QueuedConnection);
    //Qt4风格
    connect(this,SIGNAL(testSingal(QString)),this,SLOT(testSlot(QString)),Qt::QueuedConnection);

    QString path="test";
    emit testSingal(path);

常见的lambda表达式使用(qt线程)

    QThread * th=QThread::create([=]{
        qDebug()<<"test";
    });
    connect(th,&QThread::destroyed,th,&QThread::deleteLater);
    th->start();

你可能感兴趣的:(C++,qt,lambda,qt,c++,thread)