Petr
Petr

Reputation: 14505

How to implement shortcut input box in Qt

In software like qtcreator you can see things like this:

enter image description here

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

Answers (2)

svlasov
svlasov

Reputation: 10455

In case you need the widget for Qt 4.x, I have implemented one previously. Three key parts are:

  1. read user input
  2. convert it to human readable string
  3. create QKeySequence using the string

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

fxam
fxam

Reputation: 3982

Use QKeySequenceEdit, available since Qt 5.2. It allows you to record shortcut key like in Qt Designer.

Upvotes: 4

Related Questions