How to use QTimer
mytimer.h:
#ifndef MYTIMER_H
#define MYTIMER_H
#include <QTimer>
class MyTimer : public QObject
{
Q_OBJECT
public:
MyTimer();
QTimer *timer;
public slots:
void MyTimerSlot();
};
#endif // MYTIME
mytimer.cpp:
#include "mytimer.h"
#include <QDebug>
MyTimer::MyTimer()
{
// create a timer
timer = new QTimer(this);
// setup signal and slot
connect(timer, SIGNAL(timeout()),
this, SLOT(MyTimerSlot()));
// msec
timer->start(1000);
}
void MyTimer::MyTimerSlot()
{
qDebug() << "Timer...";
}
main.cpp:
#include <QCoreApplication>
#include "mytimer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Create MyTimer instance
// QTimer object will be created in the MyTimer constructor
MyTimer timer;
return a.exec();
}
If we run the code:
Timer...
Timer...
Timer...
Timer...
Timer...
...
resources
It's good practice to give a parent to your
QTimer
to use Qt's memory management system.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.If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.
Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.
Other way is using of built-in method start timer & event TimerEvent.
Header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
int timerId;
protected:
void timerEvent(QTimerEvent *event);
};
#endif // MAINWINDOW_H
Source:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timerId = startTimer(1000);
}
MainWindow::~MainWindow()
{
killTimer(timerId);
delete ui;
}
void MainWindow::timerEvent(QTimerEvent *event)
{
qDebug() << "Update...";
}