【QT】解决Qt发送信号指定重载

现象

信号发送者找不到正确的信号函数

connect(ui->LSpinBox,&QSpinBox::valueChanged,ui->hSlider,&QSlider::setValue);

QSpinBox的valueChanged函数分为int和QString两种,存在函数重载,需让编译器加以区分。
不区分的话会爆出:

error: C2664: 
“QMetaObject::Connection QObject::connect(const QObject *,const char *,const char *,Qt::ConnectionType) const: 
无法将参数 2 从“overloaded-function”转换为“const char *

解决方案

使用QOverload

Qt5官方文档推荐使用的方式

 connect(comboBox, QOverload<int>::of(&QComboBox::activated),
      [=](int index){ /* ... */ });
 connect(comboBox, QOverload<const QString &>::of(&QComboBox::activated),
      [=](const QString &text){ /* ... */ });
auto qOverload(T functionPointer)
Returns a pointer to an overloaded function. The template parameter is the list of the argument types of the function. functionPointer is the pointer to the (member) function:
     struct Foo {
         void overloadedFunction();
         void overloadedFunction(int, const QString &);
     };
     ... qOverload<>(&Foo::overloadedFunction)
     ... qOverload<int, const QString &>(&Foo::overloadedFunction)
If a member function is also const-overloaded qConstOverload and qNonConstOverload need to be used.
qOverload() requires C++14 enabled. In C++11-only code, the helper classes QOverload, QConstOverload, and QNonConstOverload can be used directly:
     ... QOverload<>::of(&Foo::overloadedFunction)
     ... QOverload<int, const QString &>::of(&Foo::overloadedFunction)
Note: Qt detects the necessary C++14 compiler support by way of the feature test recommendations from C++ Committee's Standing Document 6.
This function was introduced in Qt 5.7.
See also qConstOverload(), qNonConstOverload(), and Differences between String-Based and Functor-Based Connections.

使用带有参数类型的SLOT和SIGNAL宏来解决发送信号时指定重载的问题

QButtonGroup buttonGroup;
connect(&buttonGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(handleButtonClicked(QAbstractButton*)));
connect(&buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(handleButtonClicked(int)));

使用指针

创建一个函数指针用于保存指定的函数地址:

void (QComboBox:: * activatedInt)(int) = &QComboBox::activated;
void (QComboBox:: * activatedString)(QString) = &QComboBox::activated;
 connect(comboBox, activatedInt,
      [=](int index){ /* ... */ });
 connect(comboBox, activatedString,
      [=](const QString &text){ /* ... */ });
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

√沫影

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值