Search code examples
c++qtqt5keyboard-shortcutskey-bindings

Qt(c++) Keybinding with button(for my developing application)


I want to write a function that will work with keybinding for the application I am developing on the Qt platform, but I could not find any example that will work for me, like the picture I added from the discord application, can you help me?

Discord keybinding


Solution

  • If you want user to hit a key combination for a selection then just create a class inheriting QLinEdit (even QLabel would work) and override keyPressEvent, void QLineEdit::keyPressEvent(QKeyEvent *event); and then use QKeyEvents function to get key and modifiers (shift, ctrl etc.). Just read the Qt Docs about it. Depending on the key and modifiers, write the modifier name + key's text (e.g. Ctrl + N).

    To hold actions (QAction), just use std::map<QString,QAction*> or QMap<QString,QAction*> and register/add your QAction objects in the map and assuming your class' name is MyClass and it has getKeyString() , to return key combination as QString, then you will just do,

    QString str = MyClassObj.getKeyString();
    QKeySequence ks(str);
    actionMap.at("NewFile")->setShortcut(ks);