Reputation: 3
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?
Upvotes: 0
Views: 357
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 QKeyEvent
s 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
Reputation: 6329
You question is slightly fuzzy, there are a few aspects associated with key bindings.
QAction
, QShortcut
, QMenu
.QKeySequenceEdit
which helps you entering a new shortcut key sequence for an action.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