Qt can't connect a subclass of QGraphicsView signal (not inherited) to SLOT

旧街凉风 提交于 2019-12-11 10:42:44

问题


I defined class MyGraphicsView, a subclass of QGraphicsView. Than, I add a signal test() in MyGraphicsView. In my MainWindow class, I have MyGraphicsView* myView and I connect like:

connect(myView, SIGNAL( test() ) , this, SLOT( zoom() )) ;

But I got:

    QObject::connect: No such signal QGraphicsView::test() in ..\Proto_version_2\mainwindow.cpp:73

回答1:


In order to use slots and signals in a class, it must be derived from either QObject or a QObject derived class and your class must include the Q_OBJECT macro

class MyClass : public QGraphicsView
{
    Q_OBJECT // Without this macro, signals and slots will not work

    public:
        MyClass(QObject* parent);
};

The Q_OBJECT macro allows classes to use QT's C++ extensions. As the documentation states: -

The Meta-Object Compiler, moc, is the program that handles Qt's C++ extensions. The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.

Note, however that Qt 5 provides an additional connect call, which warns if the Q_OBJECT is missing: -

connect(myView, QMainView::test, myClassObj, MyClass::zoom);

In this case, the 2nd and 4th argument are pointers to the functions. In addition, run-time checking of the connect call is performed. You can read more about this here.



来源:https://stackoverflow.com/questions/22985894/qt-cant-connect-a-subclass-of-qgraphicsview-signal-not-inherited-to-slot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!