- Qt4的书写方式
QPushButton* button = new QPushButton("Quit");
connect(button, SIGNAL(clicked()), &a, SLOT(quit()));
这种写法没有编译错误,而是在运行时给出错误,无疑会增加程序的不稳定性。
只有在 Debug 模式下运行时才会提示槽函数不存在,Release 模式下运行时不会给予任何错误提示。
- Qt5的书写方式
QPushButton button("Quit");
QObject::connect(&button, &QPushButton::clicked, &app,&QApplication::quit);
- C++11新方式: Lambda表达式,需要再Pro项目文件中加入 CONFIG += C++ 11
QPushButton* button = new QPushButton("Quit");
connect(button, SIGNAL(clicked()),[=](QString str){qDebug() << str;});
需要注意的一点:在进行信号槽绑定时,如果有重载,需要对成员函数进行类型转换,可以使用 C++ 的 static_cast 类型转换(编译时进行语法检查),也可以使用传统的 C 语言的强制类型转换(编译时不进行语法检查,运行时才检查),或者 C++11 的 QOverload::of,C++14 的 qOverload:
QComboBox *comboBox = new QComboBox();
comboBox->addItem("Michael");
comboBox->addItem("Kobe");
comboBox->addItem("James");
comboBox->show();
// [1]
QObject::connect(comboBox,
static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
[](int index)
{
qDebug() << index;
});
// [2]
QObject::connect(comboBox,
static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::activated),
[](const QString &text)
{
qDebug() << text;
});
// [3]: QOverload<> 里面是参数列表,of() 里面是成员函数地址
QObject::connect(comboBox,
QOverload<const QString &>::of(&QComboBox::activated),
[](const QString &text)
{
qDebug() << text;
});