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

1

1

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
Adiana answered 10/4, 2014 at 10:49 Comment(2)
Can we see your code?Sodium
Did you add Q_OBJECT in your MyGraphicsView declaration?Impacted
M
6

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.

Melissamelisse answered 10/4, 2014 at 10:59 Comment(2)
moc is always needed whether you use the old or the new syntax. The Qt 5 connect will not even compile if you attempt connection to an object without the Q_OBJECT macro.Downhaul
@KubaOber, Oops my mistake. I was writing that in a rush. I've corrected the answer.Melissamelisse

© 2022 - 2024 — McMap. All rights reserved.