PDA

View Full Version : Avoid stopping the program on QPushButton pressed



rspock
1st April 2013, 08:55
Hi,

I have to check if a button is pressed for N seconds.

I set up a timer that i start on the click button event and I check the button status on the timer timeout.

The program is frezzed, i suppose in the right way, till i release the button. The timeout event is cached only when the button is released.

Any suggestion?

Guiom
1st April 2013, 09:15
Use QTime class. Like this:



QTime _startClick; //(Attribute in .h file)

void MainWindow::on_pushButton_pressed()
{
_startClick.start();
}

void MainWindow::on_pushButton_released()
{
qDebug() << _startClick.elapsed();
}

rspock
1st April 2013, 10:05
This could be a solution but the user have to press the button and count mentally the time enlapsed while I want the action fire automatically after that time..

Guiom
1st April 2013, 10:38
Ha oki, in this case use QTimer like you said.
You can connect the timeout signal of timer in released signal of button.
On the pressed event of the button you start the timer.



// Attribute in .h file
QTimer _timer;

// In the constructor for example
connect(&this->_timer, SIGNAL(timeout()), this->ui->pushButton, SIGNAL(released()));

void MainWindow::on_pushButton_pressed()
{
_timer.start(1000);
}

void MainWindow::on_pushButton_released()
{
qDebug() << "Button pressed while 1000 ms";
_timer.stop();
}

anda_skoa
2nd April 2013, 09:38
That line 5 is probably not such a good idea. You usually don't emit abother object's signal, objects emit their own signals whenever they know it is appropriate.

If the idea is to trigger an action only if the button is pressed for a certain time, then you setup the timer with single shot and desired delay, connect the action to its timeout signal and the button's pressed signal to the timer's start slot and the button's released signal to the timer's stop slot.

If the button is released before then timer runs it it is simply stopped, if the timer runs out the action is triggered. if the button is released after that happens it will stop an already stopped timer, nothing happens.

Cheers,
_