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;
}
{
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
#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
To copy to clipboard, switch view to plain text mode
#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
) : ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btnTest_clicked()
{
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
));
}
#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));
}
To copy to clipboard, switch view to plain text mode
How can I get the asynchronous behavior, something like what we have in C#? where the Timer runs its own thread of execution?
Bookmarks