PDA

View Full Version : Stoping a Qtimer problem...!



hakermania
24th August 2010, 19:32
This is the code:

void MainWindow::on_checkBox_clicked()
{
if ( ui->checkBox->isChecked() ){
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(write_random_image()));
timer->start(1000);
}
else
timer->stop();
}
actually, I wanna program , when the checkbox is clicked and checked, the timer must start, and if it is clicked and not checked the timer to stop..
The inly issue is that I get the error:
error: ‘timer’ was not declared in this scope (this goes to timer->stop();)
Even if I declare the creation of the timer at the constructor (in a try to use it globally in the program) I cannot call it because of the same error...
So, how can I fix this? :cool:

hobbyist
24th August 2010, 20:09
I guess you want to declare your QTimer *timer as a private variable in the header of your MainWindow class, initialize it to a new QTimer(this) and connect() in the constructor, and let the click-slot handle start() and stop().

hakermania
24th August 2010, 20:17
Ammm I didn't got it...
Step 1: I have to put this at the constructor
connect(timer, SIGNAL(timeout()), this, SLOT(write_random_image()));
Step 2: I have to put this in myfile.h ????????? After the inclusions (#include <QMainWindow>)
QTimer *timer = new QTimer;
Step 3: Let the click-slot handle the start-stop? How do i do this?


Sorry but I am a beginner. Very willing to learn :o:o

Lykurg
24th August 2010, 20:19
and also you might want use a unique connection (5th parameter) that the connection is only established once, even if the check box is checked several times.

Lykurg
24th August 2010, 20:24
Sorry but I am a beginner. Very willing to learn :o:o
class Foo
{
//...
private:
QTimer *m_timer;
};

Foo::Foo(/*...*/)
{
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(write_random_image()));
}

void Foo::on_checkBox_clicked(bool checked)
{
if ( checked )
m_timer->start(1000);
else
m_timer->stop();
}

hobbyist
24th August 2010, 20:28
Ok.

In the header file of your class (probably mainwindow.h):


private:
QTimer *timer;

In the constructor MainWindow::MainWindow() of your class:


timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(write_random_image()));

In the on_checkBox_clicked() slot:


if (ui->checkBox->isChecked())
timer->start(1000);
else
timer->stop();

Also remember to #include <QTimer> somewhere (e.g. in the header file).

Edit: Too slow.. :)

hakermania
24th August 2010, 20:46
Thnk you :) It works! :cool: