I tried to use a simple QTimer
object on my window widget so that I can calculate the elapsed time a method takes to complete. But to my astonishment, the timer was blocked until the method completes execution! i.e when the method in question ends, the timer starts ticking!
Here is a sample code to demonstrate what I wrote:
#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 slots:
void on_btnTest_clicked();
void OnTimerTick();
private:
Ui::MainWindow *ui;
ulong seconds;
};
#endif // MAINWINDOW_H
And this is the cpp file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"
#include <QTimer>
#include <QtCore>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btnTest_clicked()
{
QTimer * timer = new QTimer(0);
seconds =0;
connect(timer,SIGNAL(timeout()),this,SLOT(OnTimerTick()));
timer->setInterval(100);
timer->start();
QThread::sleep(5);//simulating a method which takes 5 seconds to complete
//timer->stop();
}
void MainWindow::OnTimerTick()
{
ui->lblElapsedTime->setText(QString::number(++seconds));
}
How can I get the asynchronous behavior, something like what we have in C# i.e. where the Timer runs its own thread of execution?
Update:
Thanks for the clarification, now how can I incorporate Qthreads with the timer, Do I have to inherit from Qthreads and use timer in my child class or do I have to inherit from QTimer and have a thread executed in it! It's really confusing!
This is common behavior for Qt, WinForms, WPF etc.
All UI-related events are executed synchronously one-by-one on the UI thread. Event handlers are not expected to perform long executions to avoid blocking. If you want to execute a long task, you should do it in other thread.
QTimer
is designed to raise events on the UI thread. This is good because you are sure that no other event handlers are executing at that moment.