QT开发中文网

QKeySequenceEdit 源码

QKeySequenceEdit 是一个可以让用户编辑快捷键的小部件,它可以显示并允许用户更改一个 QKeySequence 对象。QKeySequenceEdit 提供两个信号:keySequenceChanged() 和 editingFinished()。

以下是 QKeySequenceEdit 的相关源码:

头文件:

#include <QWidget>
#include <QLineEdit>
#include <QKeySequence>

class QKeySequenceEdit : public QWidget
{
    Q_OBJECT

public:
    explicit QKeySequenceEdit(QWidget *parent = nullptr);

    void setKeySequence(const QKeySequence &keySequence);
    QKeySequence keySequence() const;

signals:
    void keySequenceChanged(const QKeySequence &keySequence);
    void editingFinished();

protected:
    void keyPressEvent(QKeyEvent *event) override;
    void focusOutEvent(QFocusEvent *event) override;
    void paintEvent(QPaintEvent *event) override;

private:
    QLineEdit *m_lineEdit;
    QKeySequence m_keySequence;
};

实现文件:

#include "qkeysequenceedit.h"
#include <QPainter>

QKeySequenceEdit::QKeySequenceEdit(QWidget *parent)
    : QWidget(parent)
{
    m_lineEdit = new QLineEdit(this);
    m_lineEdit->setReadOnly(true);
    m_lineEdit->installEventFilter(this);

    auto layout = new QHBoxLayout(this);
    layout->addWidget(m_lineEdit);
    layout->setMargin(0);
    layout->setSpacing(0);
}

void QKeySequenceEdit::setKeySequence(const QKeySequence &keySequence)
{
    if (m_keySequence != keySequence) {
        m_keySequence = keySequence;
        m_lineEdit->setText(m_keySequence.toString());
        emit keySequenceChanged(m_keySequence);
    }
}

QKeySequence QKeySequenceEdit::keySequence() const
{
    return m_keySequence;
}

void QKeySequenceEdit::keyPressEvent(QKeyEvent *event)
{
    auto key = event->key();
    auto modifiers = event->modifiers();

    if (key == Qt::Key_Escape) {
        // 禁用 Esc 键
        return;
    }

    if (key == Qt::Key_Backspace || key == Qt::Key_Delete) {
        setKeySequence(QKeySequence());
        return;
    }

    if (key == Qt::Key_Return || key == Qt::Key_Enter) {
        emit editingFinished();
        return;
    }

    // 构建新的快捷键序列
    QKeySequence newKeySequence(key | modifiers);

    if (newKeySequence.count() > 1) {
        return; // 不支持多个按键的组合
    }

    setKeySequence(newKeySequence);
}

void QKeySequenceEdit::focusOutEvent(QFocusEvent *event)
{
    QWidget::focusOutEvent(event);
    emit editingFinished();
}

void QKeySequenceEdit::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QRect rect = m_lineEdit->rect();
    painter.setPen(Qt::black);
    painter.drawRect(rect.x(), rect.y(), rect.width() - 1, rect.height() - 1);
}

QKeySequenceEdit 的实现比较简单,它使用一个 QLineEdit 来显示和编辑快捷键,用户可以在 QLineEdit 上按下一个按键来更改快捷键。当用户更改了快捷键后,QKeySequenceEdit 会发出 keySequenceChanged() 信号。如果用户结束了编辑(通常是通过离开小部件或按下 Enter 键),则会发出 editingFinished() 信号。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=175

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?