使用对象类型的接口类来连接虚拟信号

时间:2016-08-28 22:18:51

标签: c++ qt

作为Connection of pure virtual signal of interface class的后续问题,我想知道如何通过在构造时使用该基类的推导类型来连接接口类的信号,而不是派生类的信号。当迭代基类对象集合时(参见cpp文件中的示例)

,这将非常有用

当我尝试连接AnimalInterface * dog2 = new Dog;的对象时,会出现错误qt_metacall is not a member of 'AnimalInterface'static assertion failed: No Q_OBJECT in the class with the signal

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

class AnimalInterface{
public:
    virtual ~AnimalInterface();

    virtual void makeSound() = 0;

/*signals*/
    virtual void madeSound() = 0;
};
Q_DECLARE_INTERFACE(AnimalInterface,"interface")




class Dog : public QObject, public AnimalInterface
{
    Q_OBJECT
    Q_INTERFACES(AnimalInterface)
public:
    void makeSound();
signals:
    void madeSound();
};




class Widget : public QWidget
{
    Q_OBJECT
    Dog *dog_;
public:
    Widget(QWidget *parent = 0);
    ~Widget();

    template< class T,
              typename =
                typename std::enable_if<std::is_base_of<AnimalInterface, T>::value>::type >
    void listenToAnimal(T * animal) {
      connect(animal, &T::madeSound, this, []{ qDebug() << "animal made sound"; });
    }
};

CPP:

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    dog_ = new Dog;
    AnimalInterface *dog2 = new Dog;

    listenToAnimal(dog_);
    listenToAnimal(dog2); // Error: qt_metacall is not a member of 'AnimalInterface'

    dog_->makeSound();
    dog2->makeSound();
}

0 个答案:

没有答案