PDA

View Full Version : Keybord shortcuts for hidden widgets / actions



Scope
3rd April 2016, 16:57
In menubar I have action "Show menu" which is checkable. For that action I have also shortcut and it works great only when menu is visible. When menubar is not visible then shortcut does not work.

How I can implement shortcuts which will work with not visible / hidden actions in menubar?
Thanks,

Added after 41 minutes:

Ok, I found solution - reimplement parent QWidget::keyPressEvent(QKeyEvent *event);



void MyWidget::keyPressEvent(QKeyEvent *event)
{
if( event->modifiers() == Qt::ControlModifier ) {
if( event->key() == Qt::Key_M )
// show my menubar
}


but now second question - is it the best solution for that purpose?

anda_skoa
3rd April 2016, 18:33
For a global shortcut I would go for a global event filter, to be sure you catch it independent of which widget has focus.

Cheers,
_

Scope
4th April 2016, 08:26
anda_skoa you mean something like that:

main.cpp


int main(int argc, char *argv[])
{

QApplication app(argc, argv);
MyWidget w;
app.installEventFilter(&w);
w.show();

return app.exec();
}


event filter in MyWidget


bool MyWidget::eventFilter(QObject *object, QEvent *event)
{
if ( event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if( keyEvent->modifiers() == Qt::ControlModifier ) {
switch (keyEvent->key()) {
case Qt::Key_M:
ui->actionShow_menu->setChecked(!ui->actionShow_menu->isChecked());
return true;
case Qt::Key_Left:
prevPage();
return true;
case Qt::Key_Right:
nextPage();
return true;
}

return false;
}
}

return QObject::eventFilter(object, event);
}


This way is correctly?

Next question, in eventFilter If I want to have "global event handler" I do not need check which object send current event, I am right? So I do not need line:



if( object == someWidget ) {
// task
}

Thanks,

anda_skoa
4th April 2016, 08:44
Yes, that looks good, though your switch() should have a default.

And indeed, a global shortcut should work independent of which widget the key would have originally been sent to.

Cheers,
_