gpt4 book ai didi

C++ QT : Function Taking Pointer To Signal And Slot Function

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:17 26 4
gpt4 key购买 nike

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 始终保持不变。所以该方法需要将 signalslot 作为参数。 slot 函数总是在 client.h 中定义。

没有参数的新函数的方法体如下所示:

void Client::connectToMqttSignal(){}

我可以为参数使用哪种类型?我可以通过设置特定类型而不在运行时检查类型 ID 来指定我只需要来自 QMqttClientSignal 函数吗?将 Slot 作为参数传递的好方法是什么?

我在这里读到关于信号和槽的内容:

https://doc.qt.io/qt-5/signalsandslots.html

QMqttCLient的文档

https://doc.qt.io/QtMQTT/index.html

最佳答案

您可以使用模板将信号和槽作为参数传递。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com