作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
QT 5.1:
为了删除冗余代码,我想外包以下两个函数调用包含的公共(public)逻辑:
客户端.cpp
void Client::connectToSignals()
{
QObject::connect(Client::mqtt.get(), &QMqttClient::connected, this,
&Client::onConnected);
QObject::connect(Client::mqtt.get(), &QMqttClient::disconnected, this,
&Client::onDisconnected);
}
因此 Client::mqtt.get()
和上下文 this
始终保持不变。所以该方法需要将 signal
和 slot
作为参数。 slot
函数总是在 client.h
中定义。
没有参数的新函数的方法体如下所示:
void Client::connectToMqttSignal(){}
我可以为参数使用哪种类型?我可以通过设置特定类型而不在运行时检查类型 ID 来指定我只需要来自 QMqttClient
的 Signal
函数吗?将 Slot
作为参数传递的好方法是什么?
我在这里读到关于信号和槽的内容:
https://doc.qt.io/qt-5/signalsandslots.html
QMqttCLient
的文档
最佳答案
您可以使用模板将信号和槽作为参数传递。
template <typename Func1, typename Func2>
static inline QMetaObject::Connection conWrapper(const typename QtPrivate::FunctionPointer<Func1>::Object *sender, Func1 signal,
const typename QtPrivate::FunctionPointer<Func2>::Object *receiver, Func2 slot,
Qt::ConnectionType type = Qt::AutoConnection)
{
return QObject::connect(sender, signal, receiver, slot, type);
}
示例用法语法:
conWrapper(this, &MainWindow::someSignal, this, &MainWindow::someSlot);
您只需在函数内将发送方替换为 Client::mqtt.get()
并将接收方替换为 this
并删除 2 个参数以满足您的要求。
关于C++ QT : Function Taking Pointer To Signal And Slot Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49716158/
我是一名优秀的程序员,十分优秀!