PDA

View Full Version : Handle KeyRelease Events inside a while loop



u2bpavankumar
30th June 2015, 15:52
Hi,

I am working on an application where I need to detect Keypress/Release events from inside a while loop

Below is my code snippet



void TabDialog::keyPressEvent(QKeyEvent *event)
{

switch (event->key()) {
case Qt::Key_F1:
{

qDebug()<<"Inside Key F1 Press Event";
while(i>0 )
{
qDebug()<<"Inside while loop";
usleep(1000000);

if(releaseFlag==1)
{
releaseFlag=0;
break;
}
i--;
}

releaseFlag=0;
}


default:
break;
}
}

void TabDialog::keyReleaseEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_F1:
{
releaseFlag=1;
qDebug()<<"Inside Key F1 Release Event";

}
break;
default:
break;
}
}


I have keypress event where in which I have a while loop which is going to execute for 10 iterations. Now if I release the F1 key (before completing 10 iterations), "releaseFlag" is not set to 1 and while loop is not getting break immediately. It was only after executing the while loop for 10 iterations I can see the change in "releaseFlag" value.

Below is the output



Inside Key F1 Press Event
Inside while loop
Inside while loop
Inside while loop
Inside while loop
Inside while loop
Inside while loop
Inside while loop
Inside while loop
Inside while loop
Inside while loop
Inside Key F1 Release Event

I want to identity the release event immediately and break the while loop..

Can someone guide me how to handle this?

Regards,
Pavan

stampede
30th June 2015, 15:57
Can someone guide me how to handle this?
Drop the while/sleep approach and code something based on QTimer. In your code control doesn't have a chance to return to the event loop and process any other events.

u2bpavankumar
2nd July 2015, 12:47
Hi stampede,

I have replaced while/sleep with timers and now it was working as expected. Thanks a lot

Regards,
Pavan