解决QT函数指针方式信号槽的连接失败的问题
问题描述
某些类存在信号重载,连接无法确认具体的发送信号的函数,导致连接失败,问题转变成,如何区分重载函数的函数指针
如QComboBox类有两个改变信号
void currentIndexChanged(int index);
void currentIndexChanged(const QString &);
解决方法
- 可以定义函数指针类型指向函数
void (QComboBox::*changeIndex)(int) = &QComboBox::currentIndexChanged;
void (QComboBox::*changeString)(const QString &) = &QComboBox::currentIndexChanged;
void (QAbstractSocket::*errorOcrrend)(QAbstractSocket::SocketError) = &QAbstractSocket::error;
QObject::connect(m_socket,
errorOcrrend, this,
[this](QAbstractSocket::SocketError /*error*/)
{
if (m_socket->state() == QAbstractSocket::UnconnectedState)
{
cleanupTransactionStore();
setState(ModbusDevice::UnconnectedState);
}
setError(ModbusClient::tr("TCP socket error (%1).").arg(m_socket->errorString()),
Error::ConnectionError);
});
- 强制转换函数指针类型
connect(ui->comboBox,static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),this,&Widget::onCurrentIndexChanged);
connect(ui->comboBox,static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::currentIndexChanged),this,&Widget::onCurrentStringChanged);
- 使用QOverload