qttimer

How to use QTimer


In Qt I'm trying to set a QTimer that calls a function called "update" every second. Here is my .cpp file:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include "QDebug"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(1000);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::update()
{
    qDebug() << "update";
}

and the main:

#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

The project is being build, but it doesn't execute update, since the line "update" is not showing anywhere... Does anybody see what I´m doing wrong?


Solution

    1. It's good practice to give a parent to your QTimer to use Qt's memory management system.

    2. update() is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.

    3. If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.

    4. Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.