Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Interface for class in Qt. How?



  • Hello all!
    Is there something special in Qt if I am going to define interface class in Qt? Or it's better to deal through the class inheritance and reload methods if need? The question is only about Qt not about pure C++.


  • Moderators

    The question is only about Qt not about pure C++.

    Qt is pure C++ so I'm not sure what you mean. You can have interface (pure virtual class to be exact) class and have a QObject derived class that inherits from it.



  • @Chris-Kawa I mean to use Q_DECLARE_INTERFACE(Interface, "Interface") and Q_INTERFACE in object (something like this) or using direct class inheritance when I am using empty methods prototyping in template class and reload them in class that I am using instead of first way. What is better to use in qt?


  • Moderators

    @bogong Sorry, I'm still not sure what you mean by "reloading class methods". Using Q_DECLARE_INTERFACE registers given class in Qt's meta system. Using Q_INTERFACES tells the meta-system that your class implements that interface. Both those things combined allow you to use qobject_cast to cast your class to that interface.

    There's no better or worse. The question is do you need that functionality for something. If not then don't pay for what you don't use. That's the mantra of C++.



  • @Chris-Kawa I need to implement interface/abstract class. I am seeking solution for it IN QT. There are options to use:

    • through Q_INTERFACE declaration
    • through defining template class within virtual methods and inheriting it directly without Q_INTERFACE and override

    The question what is better to use in QT?

    Sorry wrong term. Not reload, I mean override.


  • Moderators

    It's not one or the other. It's one on top of the other.

    You can do

    class Foo : public QObject, public SomeInterface
    {
        Q_OBJECT
    }
    

    and that does one thing. Then you can add

    class Foo : public QObject, public SomeInterface
    {
        Q_OBJECT
        Q_INTERFACES(SomeInterface)
    }
    

    and that adds some extra functionality (qobject_cast for example).

    In both cases you need to inherit from that interface class and in both cases you need to override the virtual methods of that interface. The only thing it does is adds more meta-data info about your class which enables extra functionality, so again - there's no better or worse. It's just a question of do you need it.



  • @Chris-Kawa said in Interface for class in Qt. How?:

    and that adds some extra functionality (qobject_cast for example)

    Thx ... This point is what I've been missing. Issue closed.


Log in to reply