Mitko
Mitko

Reputation: 3

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

Upvotes: 0

Views: 357

Answers (2)

Keshav Sahu
Keshav Sahu

Reputation: 108

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);

Upvotes: 0

Jens
Jens

Reputation: 6329

You question is slightly fuzzy, there are a few aspects associated with key bindings.

  1. At the start of the application, you can assign default shortcut keys to actions and menus, see the documentation on QAction, QShortcut, QMenu.
  2. If you need a dialog which allows changing a key binding, you can easily create a dialog yourself. See the documentation on QKeySequenceEdit which helps you entering a new shortcut key sequence for an action.
  3. Last but not least, you need to bind your modified key sequences to your actions. You can do this by deriving a class from QAction. Find these actions by searching all objects with mainWindow->findChildren<YourActionClass*>() and modify the keyboard shortcut with the results from your dialog. This derived class could also store the default binding, the icon (your users might like to modify icons perhaps) etc.

All this is quite straight forward.

Upvotes: 1

Related Questions