简体   繁体   中英

How to implement shortcut input box in Qt

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?

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM