Qt connect中的 Lambda

来源:互联网 发布:lbp算法matlab 编辑:程序博客网 时间:2024/05/14 06:02

Qt 5 使用 C++11 支持 Lambda 表达式,connect() 的时候如果函数名写错了就会在编译时报错,还有一点是 Lambda 表达式在需要的时候才定义,不需要声明,写起来比较简单,这对于较小的处理函数来说简直太棒了。

Qt connect中使用 Lambda

信号槽

#include <QApplication>#include <QDebug>#include <QPushButton>int main(int argc, char *argv[]) {    QApplication app(argc, argv);    QPushButton *button = new QPushButton("点击");    button->show();    QObject::connect(button, &QPushButton::clicked, []() {        qDebug() << "点击";    });    return app.exec();}

信号槽(重载)

#include <QApplication>#include <QDebug>#include <QComboBox>int main(int argc, char *argv[]) {    QApplication app(argc, argv);    QComboBox *comboBox = new QComboBox();    comboBox->addItem("林冲");    comboBox->addItem("鲁达");    comboBox->addItem("武松");    comboBox->show();    QObject::connect(comboBox, &QComboBox::activated, []() {        qDebug() << "Hello";    });    return app.exec();}

编译报错: No matching function for call to ‘connect’,原因是信号 QComboBox::activated() 有重载函数:

    void QComboBox::activated(int index)    void QComboBox::activated(const QString &text)

在进行信号槽绑定时,如果有重载,需要对成员函数进行类型转换,可以使用 C++ 的 static_cast 类型转换(编译时进行语法检查),也可以使用传统的 C 语言的强制类型转换(编译时不进行语法检查,运行时才检查)

#include <QApplication>#include <QDebug>#include <QComboBox>int main(int argc, char *argv[]) {    QApplication app(argc, argv);    QComboBox *comboBox = new QComboBox();    comboBox->addItem("林冲");    comboBox->addItem("鲁达");    comboBox->addItem("武松");    comboBox->show();    QObject::connect(comboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), [](int index) {        qDebug() << index;    });    QObject::connect(comboBox, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::activated), [](const QString &text) {        qDebug() << text;    });    return app.exec();}
原创粉丝点击