Hi everyone,
I’m having trouble with a `QTimer` that doesn’t seem to trigger its slot. The timer starts without errors, but the timeout function is never called.
Here is a simplified version of my code:
#include <QApplication>
#include <QMainWindow>
#include <QTimer>
#include <QDebug>
{
Q_OBJECT
public:
MainWindow
(QWidget *parent
= nullptr
) {
connect(timer, &QTimer::timeout, this, &MainWindow::onTimeout);
timer->start(1000); // 1 second
}
private slots:
void onTimeout()
{
qDebug() << "Timer triggered";
}
};
int main(int argc, char *argv[])
{
MainWindow w;
w.show();
return a.exec();
}
#include <QApplication>
#include <QMainWindow>
#include <QTimer>
#include <QDebug>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::onTimeout);
timer->start(1000); // 1 second
}
private slots:
void onTimeout()
{
qDebug() << "Timer triggered";
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
To copy to clipboard, switch view to plain text mode
The application runs fine, but "Timer triggered" never appears in the console.
Am I missing something related to the event loop or object lifetime?
Is there something wrong with how I’m creating or connecting the timer?
Bookmarks