Good day! I wrote a small class and QTimer in it, but when you call start (), the application enters an eternal loop. From my point of view, all the rules, but apparently, I did not take into account something.

myclass.h

#include <QObject> #include <QTimer> class MyClass: public QObject { Q_OBJECT public: MyClass(QObject *parent = 0); void start(); virtual ~MyClass(); public slots: void showMessage(); private: QTimer *timer; }; 

myclass.cpp

 #include "myclass.h" #include <iostream> MyClass::MyClass(QObject *p): QObject(p) { timer = new QTimer(this); QObject::connect(timer, &QTimer::timeout, this, &MyClass::showMessage); } void MyClass::showMessage() { timer->stop(); std::cout << "Hello World!"; } void MyClass::start() { timer->start(1); } MyClass::~MyClass() { delete timer; } 

main.cpp

 #include <QCoreApplication> #include "myclass.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyClass my; my.start(); return a.exec(); } 
  • This a.exec() starts the "eternal" Qt message loop, read how it works in the help - this is the basis of any Qt program (any program with an interface, if you dig deeper) - ixSci
  • @ixSci how exec () works, I understand, the problem is that the timeout timer does not occur. - Max
  • By the way, there is no need to do delete timer , since it has a parent. And for a one-time operation there is singleShot - StrangeOwl

1 answer 1

I do not understand what the question is. I have this code going and working correctly. If you do not see "Hello World!" then these are problems as I think with the conclusion (it most likely derives, you just don’t see where). You can try to create a Widget that would be clearly visible, noticeable. If the question is why the application does not stop - and why should it? The timer itself stops, but the event loop continues. You can try to add for example exit(0) to your slot - then the application will end (with code 0).