QShortcut multiple widget instances



  • I have a custom QWidget that deploys QShortcuts 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 widgets QShortcuts are "enabled". Apparently I am wrong.

    What is the proper solution to handle this problem?


  • Moderators

    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 inside someWidget1 and sh2 inside someWidget2.



  • Thank you Sir, this helped a lot!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.