限制 QKeySequence/QKeySequenceEdit 只有一个快捷方式

Limit QKeySequence/QKeySequenceEdit to only one shortcut

是否可以限制QKeySequenceQKeySequenceEdit中只显示一个快捷方式?目前它最多支持 4 个快捷方式。我的应用程序仅支持一个快捷方式的键序列,例如Ctrl+ACtrl+C 而不是例如Ctrl+A, DCtrl+C, X, Z.

是否可以将 QKeySequenceQKeySequenceEdit 限制为仅一个键序列?

解决了它,不是最好的解决方案但很快...如果你想要更多自定义的东西,我认为你必须自己构建它...

customkeysequenceedit.h:

#ifndef CUSTOMKEYSEQUENCEEDIT_H
#define CUSTOMKEYSEQUENCEEDIT_H

#include <QKeySequenceEdit>

class QKeyEvent;

class CustomKeySequenceEdit : public QKeySequenceEdit
{
    Q_OBJECT

public:
    explicit CustomKeySequenceEdit(QWidget *parent = 0);
    ~CustomKeySequenceEdit();

protected:
    void keyPressEvent(QKeyEvent *pEvent);
};

#endif // CUSTOMKEYSEQUENCEEDIT_H

customkeysequenceedit.cpp:

#include "customkeysequenceedit.h"

#include <QKeyEvent>

CustomKeySequenceEdit::CustomKeySequenceEdit(QWidget *parent) : QKeySequenceEdit(parent) { }

CustomKeySequenceEdit::~CustomKeySequenceEdit() { }

void CustomKeySequenceEdit::keyPressEvent(QKeyEvent *pEvent)
{
    QKeySequenceEdit::keyPressEvent(pEvent);

    QKeySequence seq(QKeySequence::fromString(keySequence().toString().split(", ").first()));
    setKeySequence(seq);

}

您可以使用 QKeySequence[] 运算符:http://doc.qt.io/qt-5/qkeysequence.html#operator-5b-5d

所以在你的接口构造函数中,这样写:

connect(ui->editShortcut, &QKeySequenceEdit::editingFinished, 
        this, &dialog::truncateShortcut);

并将此私有方法添加到您的对话框中 class:

void dialog::truncateShortcut()
{
    int value = ui->editShortcut->keySequence()[0];
    QKeySequence shortcut(value);
    ui->editShortcut->setKeySequence(shortcut);
}

这样做,你就完全尊重API,不依赖,性格,这是相当冒险的。