当已经从QObject/QWidget派生实现类时,如何在抽象类/接口(interface)中声明Qt信号?
class IEmitSomething
{
public:
// this should be the signal known to others
virtual void someThingHappened() = 0;
}
class ImplementEmitterOfSomething : public QWidget, public IEmitSomething
{
// signal implementation should be generated here
signals: void someThingHappended();
}
最佳答案
正如我在最近几天发现的那样... Qt的实现方式是这样的:
class IEmitSomething
{
public:
virtual ~IEmitSomething(){} // do not forget this
signals: // <- ignored by moc and only serves as documentation aid
// The code will work exactly the same if signals: is absent.
virtual void someThingHappened() = 0;
}
Q_DECLARE_INTERFACE(IEmitSomething, "IEmitSomething") // define this out of namespace scope
class ImplementEmitterOfSomething : public QWidget, public IEmitSomething
{
Q_OBJECT
Q_INTERFACES(IEmitSomething)
signals:
void someThingHappended();
}
现在,您可以连接到这些接口(interface)信号。
如果在连接信号时无法访问实现,则connect语句将需要动态转换为
QObject
:IEmitSomething* es = ... // your implementation class
connect(dynamic_cast<QObject*>(es), SIGNAL(someThingHappended()), ...);
...并且通过这种方式,您不必强制将实现类公开给订阅者和客户端。是的!