So, I have an application where if a particular button is kept pressed it plays an audio device, when the button is released it stops the audio device. I use keyPressEvent
and KeyReleaseEvent
to implement this which is similar to the code below:
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if(event->isAutoRepeat())
{
event->ignore();
}
else
{
if(event->key() == Qt::Key_0)
{
qDebug()<<"key_0 pressed"<<endl;
}
else
{
QWidget::keyPressEvent(event);
}
}
}
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
if(event->isAutoRepeat())
{
event->ignore();
}
else
{
if(event->key() == Qt::Key_0)
{
qDebug()<<"key_0 released"<<endl;
}
else
{
QWidget::keyReleaseEvent(event);
}
}
}
But apparently isAutoRepeat
function isn't working as I can see continuous print out of key_0 pressed
and key_0 released
despite the fact I haven't released the 0 key after I have pressed it. Is my code wrong or something else is wrong?
Thanks.
EDIT
I think this is happening because the MainWindow
loses the keyboard focus. How can I actually find out which widget has the focus? I'm actually using some widgets when Qt::Key_0
pressed, but I thought I set all those possible widgets to Qt::NoFocus
, I guess it's not working.
I'm trying to know which widget has the focus by doing the following:
QWidget * wigdet = QApplication::activeWindow();
qDebug()<<wigdet->accessibleName()<<endl;
but it always prints an empty string. How can I make it print the name of the widget which has the keyboard focus?
MainWindow
orConsoleMainWindow
? Seems like there is a typo in your question – IAmInPLSNote that if the event is a multiple-key compressed event that is partly due to auto-repeat, this function could return either true or false indeterminately
. Are you in this case? – IAmInPLS