QT : Templated Q_OBJECT class

后端 未结 4 749
予麋鹿
予麋鹿 2020-11-29 03:26

Is it possible to have a template class, which inherit from QObject (and has Q_OBJECT macro in it\'s declaration)?

I would like to create something like adapter for

4条回答
  •  感情败类
    2020-11-29 04:04

    It is still not possible to mix templates and Q_OBJECT but depending on your use case you may use the new 'connect'-syntax. This allows at least the usage of template-slots.

    Classical non-working approach:

    class MySignalClass : public QObject {
      Q_OBJECT
    public:
    
    signals:
      void signal_valueChanged(int newValue);
    };     
    
    
    template
    class MySlotClass : public QObject {
      Q_OBJECT
    public slots:
      void slot_setValue(const T& newValue){ /* Do sth. */}
    };
    

    Desired usage but not compilable:

    MySignalClass a;
    MySlotClass b;
    
    QObject::connect(&a, SIGNAL(signal_valueChanged(int)),
                     &b, SLOT(slot_setValue(int)));
    

    Error: Template classes not supported by Q_OBJECT (For MySlotClass).

    Solution using new the 'connect'-syntax:

    // Nothing changed here
    class MySignalClass : public QObject {
      Q_OBJECT
    public:
    
    signals:
      void signal_valueChanged(int newValue);
    };
    
    
    // Removed Q_OBJECT and slots-keyword
    template
    class MySlotClass : public QObject {  // Inheritance is still required
    public:
      void slot_setValue(const T& newValue){ /* Do sth. */}
    };
    

    Now we can instantiate desired 'MySlotClass'-objects and connect them to appropriate signal emitters.

      MySignalClass a;
      MySlotClass b;
    
      connect(&a, &MySignalClass::signal_valueChanged,
              &b, &MySlotClass::slot_setValue);
    

    Conclusion: Using template-slots is possible. Emitting template signals is not working since a compiler error will occur due to missing Q_OBJECT.

提交回复
热议问题