Correctly detecting Ctrl + key click

  • In an event handler like QWidget::keyPressEvent() I'd like to know if user has clicked a key with a modifier (e.g. Ctrl+C for my own purposes). But look at the documentation:

    Returns the keyboard modifier flags that existed immediately after the event occurred.

    Warning: This function cannot always be trusted. The user can confuse it by pressing both Shift keys simultaneously and releasing one of them, for example. warns not to use this, and suggests:

    It should be noted this may not reflect the actual keys held on the input device at the time of calling but rather the modifiers as last reported in one of the above events.

    So is either one of them actually any better/more reliable than the other? Reading it seems to me that neither correctly guarantees to detect, say, Ctrl+C being pressed? So what should I do?

  • Lifetime Qt Champion


    Depending on what you want to do wouldn't a QAction with a QShortCut fill the bill ?

  • @SGaist
    Just to say: Thanks, I have not ignored your suggestion, I just haven't had time yet to look into it. I need to recognise Ctrl+C for Copy-to-clipboard when on a selected row in a QTableView etc. (that's what the existing code allows for). If I can change it to a "higher-level" than the physical keypress using your recommendation I shall do so, and report back....

  • @SGaist
    Finally got back to this. Indeed an "anonymous" action on the QTableView of QAction.setShortcut(QKeySequence.Copy) for copying the table content is a much better solution than needing to detect key presses as per the old code, so thank you.

Log in to reply

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