[英]C++ QT: Function Taking Pointer To Signal And Slot Function
QT 5.1: QT 5.1:
To remove redundant code I want to outsource the common logic the following two function calls contain: 为了删除冗余代码,我想将以下两个函数调用包含在通用逻辑中:
client.cpp client.cpp
void Client::connectToSignals()
{
QObject::connect(Client::mqtt.get(), &QMqttClient::connected, this,
&Client::onConnected);
QObject::connect(Client::mqtt.get(), &QMqttClient::disconnected, this,
&Client::onDisconnected);
}
So Client::mqtt.get()
and the context this
always stay the same. 因此, Client::mqtt.get()
和上下文this
始终保持不变。 So the method needs to take the signal
and slot
as params. 因此该方法需要将signal
和slot
作为参数。 The slot
function is always defined in client.h
. slot
功能始终在client.h
定义。
The method body of the new function without params looks like this: 不带参数的新函数的方法主体如下所示:
void Client::connectToMqttSignal(){}
Which type can I use for the params? 我可以使用哪种类型的参数? Can I specify that I only want Signal
functions from QMqttClient
by setting a specific type without checking the type id at runtime? 是否可以通过设置特定类型而不在运行时检查类型ID来指定仅希望QMqttClient
Signal
功能? And what is a good way to pass the Slot
as parameter? 将Slot
作为参数传递的好方法是什么?
I read here about signals and slots: 我在这里阅读有关信号和插槽的信息:
https://doc.qt.io/qt-5/signalsandslots.html https://doc.qt.io/qt-5/signalsandslots.html
The documentation for QMqttCLient
QMqttCLient
的文档
https://doc.qt.io/QtMQTT/index.html https://doc.qt.io/QtMQTT/index.html
You can use a template to pass signals and slots as parameters. 您可以使用模板将信号和插槽作为参数传递。
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);
}
Example usage syntax: 使用语法示例:
conWrapper(this, &MainWindow::someSignal, this, &MainWindow::someSlot);
You just need to replace sender to Client::mqtt.get()
and receiver to this
inside the function and remove 2 parameters to meet your requirements. 你只需要更换发送到Client::mqtt.get()
和接收到this
功能里面,并删除2个参数满足您的要求。
If you have a particular signature in mind, then it could be as simple as: 如果您有一个特定的签名,那么它可以很简单:
QMetaObject::Connection Client::connectMqtt((QMqttClient::*signal)(),
(Client::*slot)())
{
return connect(mqtt.get(), signal, this, slot);
}
Otherwise, the templated version in the other answer is more flexible. 否则,另一个答案中的模板化版本会更加灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.