信号槽的书写方式

  • 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;
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值