QShortcut multiple widget instances
-
I have a custom
QWidget
that deploysQShortcut
s for the Ctrl+F and Escape key sequences. Everything works great as long as I have just one instance of that custom widget. However, as soon as I create multiple instances none of the widgets react on the key sequences anymore.
I would have suspected that the widget that has focus gets the key events and therefore that widgetsQShortcut
s are "enabled". Apparently I am wrong.What is the proper solution to handle this problem?
-
Two things are important when dealing with shortcuts: shortcut parent and context. By default a shortcut has window context so you can't have two of them in different widgets inside that same window. You have to set it explicitly to something narrower, e.g.
Qt::WidgetWithChildrenShortcut
. With this setting it's important to give the shortcuts appropriate parents to scope them.auto sh1 = new QShortcut(QKeySequence::Find, someWidget1, SLOT(whatever()), nullptr, Qt::WidgetWithChildrenShortcut); auto sh2 = new QShortcut(QKeySequence::Find, someWidget2, SLOT(iDontCare()), nullptr, Qt::WidgetWithChildrenShortcut);
this way
sh1
will work insidesomeWidget1
andsh2
insidesomeWidget2
. -
Thank you Sir, this helped a lot!