连接接口中声明的QT信号

Connect QT Signals declared in interface

本文关键字:QT 信号 声明 接口 连接      更新时间:2023-10-16

有没有办法使用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子句的接口中声明,并且应该被下层类继承。