简体   繁体   中英

QT_INTERFACES and signal definitions

How to define signals in interfaces?

class ISomeInterface
{
    signals:
        virtual void added(const QString& id) = 0;
        virtual void removed(const QString& id) = 0;

    // bla, other methods
}

Afaik, signals should not virtual but if I want to define that a signal needs to be implemented in classes implementing the interface => how to do this? Or do you simply make them non-abstract... but interfaces have no Q_OBJECT declaration here! Is the correct code generated in this cases? On top... you'll need a bad (f* * *g) cast to QObject if you want to connect to the signals.

class ISomeInterface
{
    signals:
        void added(const QString& id);
        void removed(const QString& id);

    // bla, other methods
}

Or do you try to implement it that way?

class ISomeInterface : public QObject
{
    Q_OBJECT

    signals:
        void added(const QString& id);
        void removed(const QString& id);

    // bla, other methods
}

Q_DECLARE_INTERFACE(ISomeInterface, "ISomeInterface")

.. but this way I can inherit from only one interface (QObject does not support multiple inheritance).

Conclusion: As suggested, I would go with the first one.

  1. Define signals as virtual abstract protected methods. (Instead of protected you may use signal: keyword).
  2. Final object must interhit your interface and QObject
  3. Cast pointer to interface to QObject * with dynamic_cast
  4. Connect pointer to necessary slots

You may check this topic for some solutions.

Unfortunately Qt does not handle multiple inheritance from QObject (see this Q&A ), so you can't derive all your interfaces from it (otherwise you won't be able to derive from multiple interfaces). So instead you might have something like IQObject interface with

virtual QObject* qObject() = 0

method, so you don't need to cast them to QObject all the time.

As for providing interface for signals - no such thing. What you can do is make them virtual abstract, that'll work if you really need to enforce this compile-time check (because signals: is just an alias for protected: ). If you don't, just check the return value from the connect() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM