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?
The QTimer class provides timer signals and single-shot timers. It uses timer events internally to provide a more versatile timer. QTimer is very easy to use: create a QTimer, call start() to start it and connect its timeout() to the appropriate slots. When the time is up it will emit the timeout() signal.
The QTimer class provides a high-level programming interface for timers. To use it, create a QTimer , connect its timeout() signal to the appropriate slots, and call start() . From then on, it will emit the timeout() signal at constant intervals.
You can set a timer to time out only once by calling setSingleShot(true). You can also use the static QTimer::singleShot() function to call a slot after a specified interval: QTimer::singleShot(200, this, &Foo::updateCaption); In multithreaded applications, you can use QTimer in any thread that has an event loop.
Most platforms support a resolution of 1 millisecond, though the accuracy of the timer will not equal this resolution in many real-world situations. The accuracy also depends on the timer type. For Qt::PreciseTimer, QTimer will try to keep the accurance at 1 millisecond.
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..."; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With