QTimer :: singleShot () searches for the specified slot in the parent class of this object, not the object itself

I am new to Qt. I made some simple changes to an existing Qt application, but I haven't created anything from scratch yet.
I also don't have much experience with some aspects of C ++ in general (class inheritance, etc.).

I created a new Code :: Blocks Qt4 project and changed the template a bit. I added two files.
Now the project contains three files: main.cpp, app.h and app.cpp.
This is the contents of main.cpp :

#include <QTimer> #include "app.h" int main(int argc, char* argv[]) { TestApp app(argc, argv); QTimer::singleShot(1000, &app, SLOT(timeout())); return app.exec(); } 

Here is what app.h looks like :

 #ifndef APP_H_INCLUDED #define APP_H_INCLUDED #include <QApplication> class TestApp: public QApplication { public: TestApp(int &argc, char **argv); public slots: void timeout(); }; #endif 

And this is app.cpp :

 #include "app.h" #include <QDebug> TestApp::TestApp(int &argc, char **argv): QApplication(argc, argv) { } void TestApp::timeout() { qDebug() << "timeout called"; } 

I expected the program to display a timeout one second after starting. Unfortunately this does not work. When QTimer::singleShot() is called, the console says:

 Object::connect: No such slot QApplication::timeout() in [path to the main.cpp file] Object::connect: (receiver name: 'QtTests') 

I have no idea how to deal with this. Thank you in advance.

+8
c ++ inheritance qt signals-slots connect
source share
2 answers

You just miss the Q_OBJECT macro in your TestApp class:

 class TestApp: public QApplication { Q_OBJECT public: ... 

This is necessary for the entire signal / slot infrastructure to work (and get from a class for which this macro is not enough).

(Make sure you make a complete, clean build after this change - and if you are not using qmake or any other Qt build system, you need to run moc yourself.)

For reference see QObject docs:

Note that the Q_OBJECT macro is required for any object that implements signals, slots, or properties. You also need to run the Meta Object Compiler in the source file. We strongly recommend that you use this macro in all subclasses of QObject, regardless of whether they really use signals, slots, or properties, as failure to do this can lead to some functions that exhibit strange behavior.

+6
source share

You need to create a moc file that is created with qmake if you put the Q_OBJECT macro in your class.

So, to fix your example, you need your class to change to this:

 class TestApp: public QApplication { Q_OBJECT public: TestApp(int &argc, char **argv); public slots: void timeout(); }; 
+3
source share

All Articles