Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    Solved How to have QWidget keypress override main window menu shortcuts?

    General and Desktop
    2
    4
    524
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • K
      kitfox last edited by kitfox

      I'm writing a program where I'd like to have a custom widget override the keypress behavior of the main menu actions.

      When it program starts, it sets up it's main menu using QActions:

          QMenuBar* mb = new QMenuBar();
          
          QMenu* editMenu = mb->addMenu(tr("&Edit"));
      
          {    
              QAction* action = new QAction(tr("&Delete"), _mainWindow);
              action->setShortcut(QKeySequence("Delete"));
              action->setStatusTip(tr("Delete selection"));
              connect(action, &QAction::triggered, this, &Environment::deleteSelection);
              actionMap[ACTION_DELETE] = action;
          
              editMenu->addAction(actionMap[ACTION_DELETE]);
          }
          //More entries like this
          
          _mainWindow->setMenuBar(mb);
      

      My custom widget needs to do something different when Delete is pressed. I've overridden keyPressEvent, and while keyPressEvent is being called for most keypresses, any key combo that the maim menu actions have been assigned to is not making it into this method. Is there any way to have my widget handle the keypress first, and then only pass it on to the main window if it decides it doesn't need it?

          void CurvesEditor::keyPressEvent(QKeyEvent *event)
          {
              switch (event->key())
              {
              case Qt::Key_Delete:
              {
                  //Deletion code
                  return;
              }
              }
              
              QWidget::keyPressEvent(event);
          }
      
      1 Reply Last reply Reply Quote 0
      • Chris Kawa
        Chris Kawa Moderators last edited by

        In your widget override event(), check event type() and handle QEvent::ShortcutOverride to accept the event when the key sequence is QKeySequence::Delete.

        1 Reply Last reply Reply Quote 5
        • K
          kitfox last edited by

          This post is deleted!
          1 Reply Last reply Reply Quote 0
          • K
            kitfox last edited by

            That worked. Thanks!

            1 Reply Last reply Reply Quote 0
            • First post
              Last post