Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Preventing key press in a text edit



  • Hello,

    I have a simple application which host one QPlainTextEdit, I can type into it easily. But when I press a key with additional key modifier (e.g. cmd+m), the key appears in the edit, too.

    I other words, if I hit "m", "m" appears. If I hit "cmd+m", "m" appears.

    Please, how to prevent the key press if there was present a modifier? I would like "cmd+m" to do nothing unless there is a QAction defined. In other words, "cmd+z" should undo because there is undo defined, "cmd+n" should open new window if the is a QAction with "cmd+n" shortcut. But if there is no such action with shortcut I don't want the key to appear in the edit.



  • What about re-implementing QPlainTextEdit::keyPressEvent and block modified key events (check QKeyEvent::modifiers method)?



  • Thanks, that would probably work. But the thing is, Qt Creator does exhibit the wanted behavior described above and I cannot find how they do it. There is no checking of modifiers for ctrl in "basetexteditor.cpp" so I'm wondering whether there is other way of doing this..?



  • Well, definitely I have different basetexteditor.cpp file. For example this line in BaseTextEditorWidget::keyPressEvent (taken from http://qt.gitorious.org ):
    @
    } else if ((e->modifiers() & (Qt::ControlModifier|Qt::AltModifier)) != Qt::ControlModifier){
    @

    seems to block ctrl-modified key events. And there is several other places in this file where 'control' modifier, or key, is checked.



  • Right you are! Stupid me, I was looking for "ctrl" and not "ControlModifier". Thank you very much!


Log in to reply