连接接口中声明的QT信号
Connect QT Signals declared in interface
有没有办法使用Qt5样式的信号&如果在接口中声明信号,则槽位连接。
我的接口:
class IMyInterfaces{
protected:
IMyInterfaces() {} //Prohibit instantiate interfaces
public:
virtual ~IMyInterfaces(){}
signals:
virtual void notify_signal() =0;
};
Q_DECLARE_INTERFACE(IMyInterfaces, "IMyInterfaces");
和实现上述接口的类:
class MyClass : public QObject, public IMyInterfaces{
Q_OBJECT
Q_INTERFACES(IMyInterfaces) //Indicates interface implements
public:
MyClass():QObject(){
}
~MyClass(){}
signals:
void notify_signal();
};
在主程序中,我想这样做:
IMyInterfaces * myObject = new MyClass();
//Connect signal using Qt5 style (This will introduce compilation errors)
connect(myObject ,&IMyInterfaces::notify_signal, otherObject, &OtherClass::aSlot);
旧的样式可以工作,但是需要强制转换为QObject:
QObject::connect(dynamic_cast<QObject *>(m),SIGNAL(notify_signal()),other,SLOT(aSlot())); //This works but need to cast to QObject.
你可以在接口中将你的信号声明为非虚的。由于信号不会由任何满足接口的类实现,所以这将是好的。例如:
你的界面可以是这样的
#include <QObject>
class IMyInterfaces : public QObject
{
Q_OBJECT
public:
virtual ~IMyInterfaces() {}
virtual void TestNotify() = 0;
signals:
void notify_signal();
};
实现接口的类应该是这样的:
头
#include "imyinterfaces.h"
class MyClass : public IMyInterfaces
{
Q_OBJECT
public:
MyClass();
~MyClass();
void TestNotify();
};
来源#include "myclass.h"
MyClass::MyClass()
{
// Constructor stuff placed here etc.
}
MyClass::~MyClass()
{
// Cleanup placed here etc.
}
void MyClass::TestNotify()
{
emit notify_signal(); // This signal has been inherited from the interface
}
你可以这样设置通知信号:
IMyInterfaces *myObject = new MyClass();
connect(myObject, &IMyInterfaces::notify_signal, this, &MainWindow::notify_signal);
myObject->TestNotify();
听起来像Aurel Branzeanu建议的答案,但我认为看一个例子会有所帮助。
信号不能是虚拟的。可以在没有virtual子句的接口中声明,并且应该被下层类继承。
相关文章:
- Qt 信号/插槽问题
- Qt信号和插槽如果从QRunnable或其他线程调用,则不起作用
- C++Qt信号和插槽
- 使用std::move将std::unique_ptr作为qt信号参数传递
- 使用std::bind将Qt信号连接到插槽
- 如果代码中没有连接任何插槽,是否有理由发出Qt信号?
- 文档在哪里说明如果参数不是从末端删除参数,则无法从QT信号插槽连接中删除参数?
- 按钮组上的 Qt 信号未连接
- 通过排队的QT信号插槽连接发送QSHAREDPOINTERS的QVECTOR
- QT信号和插槽无法提供错误消息
- 如何监控Qt信号事件队列深度
- QT信号在虚拟机中不连接
- 为什么事件队列未处理我的QT信号
- 如何在打印机完成打印时从打印机获取Qt信号?
- 这是在Qt信号和插槽中使用参数调用函数的好方法吗?
- 删除 QObject 后 Qt 信号仍在触发
- Qt c++信号槽 - 清除信号所必需的
- 一个类中的QT信号/插槽,但从不同的线程发出
- QT:C 信号到QML连接
- 来自静态方法的QT信号