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(); }
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) - ixScidelete timer, since it has a parent. And for a one-time operation there is singleShot - StrangeOwl