Search code examples
c++qtqobject

Qt interfaces class


How can I create an interface class, something like this :

template<typename file_system_t>
    class ireciver_intervace : public QObject
    {
        public:
        typedef typename file_system_t::file_system_item file_system_item;
    public Q_SLOTS:
        virtual void dataChangeItem(file_system_item *item)=0;
        virtual void removeItem(file_system_item *item)=0;
        virtual void insertItem(file_system_item *item)=0;
    };

and derived class

class FileItemModel:public QAbstractItemModel ,public ireciver_intervace<file_system>
        {
            Q_OBJECT
        }

When I inherit from this class I get an error mentioning ambiguous conversions. I understand this is the right behavior of the compiler, but how can I get interfaces slots for my future classes? Maybe I must use the Q_DECLARE_INTERFACE macro?


Solution

  • QObject subclasses with signal/slot functionality can't be templated.

    You can simply drop the QObject inheritance of your interface, the rest will be fine. It's no problem to define a (pure) virtual function and then (in the subclass) make a slot out of it by putting it in the slots section of your subclass:

    template<typename file_system_t>
    class ireceiver_interface
    {
    public:
        typedef typename file_system_t::file_system_item file_system_item;
    
        // pure virtual functions (NO SLOTS!):
        virtual void dataChangeItem(file_system_item *item)=0;
        virtual void removeItem(file_system_item *item)=0;
        virtual void insertItem(file_system_item *item)=0;
    };
    

    class FileItemModel: public QAbstractItemModel,
                         public ireceiver_interface<file_system_t>
    {
        Q_OBJECT
        ...
    public slots:
        // implementations (slots):
        virtual void dataChangeItem(file_system_item *item);
        virtual void removeItem(file_system_item *item);
        virtual void insertItem(file_system_item *item);
        ...
    }
    

    However, the idea of an interface is to define what functions a concrete class has to implement. Here, the interface can't force the subclass to define those functions as slots, it can also define them as non-slot functions. This minor problem can't be solved. Even if the interface could be a QObject, the subclass could then decide to re-implement those methods as non-slots!

    Note that you have two typos in your class name: It's receiver, not reciver and it's interface, not intervace.