PDA

View Full Version : Timer doesn't stop



smoon
5th March 2011, 13:04
Hi,

I have the problem, that the timer doesn't stop. What I'm doing wrong?


QBasicTimer *timer = new QBasicTimer();
timer->start(1000, this);
qDebug() << timer->timerId();
while(timer->isActive()) {
// do something
}

unit
5th March 2011, 13:39
From QT Doc: This is a fast, lightweight, and low-level class used by Qt internally. We recommend using the higher-level QTimer class rather than this class if you want to use timers in your applications. Note that this timer is a repeating timer that will send subsequent timer events unless the stop() function is called.

smoon
5th March 2011, 13:56
Also tried QTimer with setSingleShot(true), same Problem...

unit
5th March 2011, 14:42
Ok. I known problem. You should use qApp->processEvents(); in while loop. I write simple code with two type of timer. Try it.



#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QBasicTimer>
#include <QTimer>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
void timerEvent(QTimerEvent * event);

private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();

private:
Ui::MainWindow *ui;
int isRun;
QBasicTimer *basictimer;
QTimer *timer;
};

#endif // MAINWINDOW_H





#include "mainwindow.h"
#include "ui_mainwindow.h"

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

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

void MainWindow::on_pushButton_clicked()
{
timer = new QTimer();
timer->setSingleShot(true);
timer->start(5000);
int i=0;
while(timer->isActive())
{
++i;
ui->label->setText("Running " + QString::number(i));
qApp->processEvents();
}
ui->label->setText("Stopped");
delete timer;
}

void MainWindow::on_pushButton_2_clicked()
{
basictimer = new QBasicTimer();
isRun=1;
basictimer->start(5000, this);
int i=0;
while(isRun)
{
++i;
ui->label->setText("Running " + QString::number(i));
qApp->processEvents();
}
ui->label->setText("Stopped");
delete basictimer;
}

void MainWindow::timerEvent(QTimerEvent * event)
{
if(event->timerId()==basictimer->timerId())
{
basictimer->stop();
isRun=0;
}
else QMainWindow::timerEvent(event);
}

smoon
5th March 2011, 15:28
Thanks, it's working now. Used your first example with QTimer.

vinithr
11th June 2012, 16:08
Thanks This post really helped me lot.