Question

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
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top