QTimer* timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(doSomething())); timer->start(1000); // timer will invoke doSomething() every 1000ms // use deleteLater to delete the timer once it is no longer needed timer->deleteLater();
class MyObject : public QObject { Q_OBJECT public: MyObject(QObject *parent = nullptr) : QObject(parent) { QTimer::singleShot(5000, this, SLOT(checkStatus())); } private slots: void checkStatus() { // do something to check the status deleteLater(); } }; // create a new instance of MyObject and delete it after 10 seconds MyObject* obj = new MyObject(); QTimer::singleShot(10000, obj, SLOT(deleteLater()));In this example, a new object of the MyObject class is created, and a QTimer is used to invoke the checkStatus() slot after 5000ms. Once it is invoked, the deleteLater function is used to delete the object. To ensure that the object is deleted after 10 seconds, another QTimer is created and used to invoke the deleteLater function of the object. Qt library.