Reputation: 14505
In software like qtcreator you can see things like this:
Basically some box which when clicked ask you to press some keyboard combination in order to record a shortcut.
How can I create something like that in Qt? I was able so far to implement this only using a regular text box in which user had to type the combination themselves and if it wasn't correct message box appeared, but it would be much more simple if users didn't have to type things like "ctrl + f2" but instead click these keys.
Is there any Qt widget for this?
Upvotes: 3
Views: 1086
Reputation: 10455
In case you need the widget for Qt 4.x, I have implemented one previously. Three key parts are:
The widget records multiple shortcuts, like in Designer. Shortcuts can be cleared via Delete or Backspace.
#define MAX_SHORTCUTS 3
QString ShortcutLineEdit::keyEventToString(QKeyEvent *e)
{
int keyInt = e->key();
QString seqStr = QKeySequence(e->key()).toString();
if (seqStr.isEmpty() ||
keyInt == Qt::Key_Control ||
keyInt == Qt::Key_Alt || keyInt == Qt::Key_AltGr ||
keyInt == Qt::Key_Meta ||
keyInt == Qt::Key_Shift)
{
return "";
}
QStringList sequenceStr;
if (e->modifiers() & Qt::ControlModifier)
sequenceStr << "Ctrl";
if (e->modifiers() & Qt::AltModifier)
sequenceStr << "Alt";
if (e->modifiers() & Qt::ShiftModifier)
sequenceStr << "Shift";
if (e->modifiers() & Qt::MetaModifier)
sequenceStr << "Meta";
return sequenceStr.join("+") + (sequenceStr.isEmpty() ? "" : "+") + seqStr;
}
void ShortcutLineEdit::keyPressEvent(QKeyEvent *e)
{
QString text =text();
int keyInt = e->key();
bool modifiers = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier | Qt::AltModifier | Qt::MetaModifier);
if (!modifiers && (keyInt == Qt::Key_Delete || keyInt == Qt::Key_Backspace)) {
setText("");
return;
}
QString sequenceStr = keyEventToString(e);
if (sequenceStr == "") {
QLineEdit::keyPressEvent(e);
return;
}
if (text.split(", ").size() >= MAX_SHORTCUTS)
text = "";
if (!text.isEmpty())
text += ", ";
setText(text + sequenceStr);
}
void ShortcutLineEdit::apply()
{
QList<QKeySequence> sequenceList;
QStringList sequenceStrList = text().split(", ");
foreach (QString str, sequenceStrList)
sequenceList << QKeySequence(str);
// use sequenceList somehow
}
Upvotes: 3
Reputation: 3982
Use QKeySequenceEdit, available since Qt 5.2. It allows you to record shortcut key like in Qt Designer.
Upvotes: 4