我是靠谱客的博主 友好月饼,这篇文章主要介绍Qt connect中的 Lambda信号槽信号槽(重载),现在分享给大家,希望可以做个参考。

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

Qt connect中使用 Lambda

信号槽

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
#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(); }

信号槽(重载)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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() 有重载函数:

复制代码
1
2
void QComboBox::activated(int index) void QComboBox::activated(const QString &text)

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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(); }

最后

以上就是友好月饼最近收集整理的关于Qt connect中的 Lambda信号槽信号槽(重载)的全部内容,更多相关Qt内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部