qt QKeySequence详解

1、概述

QKeySequence 是 Qt 框架中的一个类,用于表示和处理键盘快捷键序列。它提供了一种方便的方式来解析、存储和比较键盘快捷键,这些快捷键通常用于触发应用程序中的特定操作或命令。QKeySequence 支持多种格式的快捷键表示,包括单个按键、按键组合以及由多个按键组成的序列。

2、重要方法

QKeySequence 类提供了多种方法来操作键盘快捷键序列,以下是一些重要的方法:

  • QKeySequence():构造函数,用于创建一个空的快捷键序列。
  • QKeySequence(const QString &key):根据提供的字符串创建一个快捷键序列。字符串可以是单个按键名称(如 "Ctrl+C"),也可以是多个按键名称的组合。
  • fromString(const QString &str, SequenceFormat format = PortableText) :静态方法,用于从字符串中解析出快捷键序列。SequenceFormat 参数指定了字符串的格式。
  • toString(SequenceFormat format = PortableText):将快捷键序列转换为字符串表示。
  • matches(const QKeySequence &seq):检查当前快捷键序列是否与另一个快捷键序列匹配。
  • count():返回快捷键序列中按键的数量。
3、常用枚举类型

SequenceFormat:

  • QKeySequence::NativeText:本地化文本格式。
  • QKeySequence::PortableText:便携文本格式。

StandardKey:

  • QKeySequence::copy:复制快捷键,通常为Ctrl+C。

  • QKeySequence::Paste:粘贴快捷键,通常为Ctrl+V。

  • QKeySequence::Undo:撤销快捷键,通常为Ctrl+Z。

  • QKeySequence::Redo:重做快捷键,通常为Ctrl+Y。

  • QKeySequence::Cut:剪切快捷键,通常为Ctrl+X。

    #include <QApplication>
    #include <QMainWindow>
    #include <QMenuBar>
    #include <QMenu>
    #include <QAction>
    #include <QMessageBox>
    #include <QKeySequence>

    class MainWindow : public QMainWindow {
    Q_OBJECT

    public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
    QMenuBar *menuBar = new QMenuBar(this);
    QMenu *fileMenu = menuBar->addMenu(tr("&File"));

    复制代码
          QAction *newAction = new QAction(tr("&New"), this);
          newAction->setShortcut(QKeySequence("Ctrl+N")); // 设置快捷键序列
          connect(newAction, &QAction::triggered, this, &MainWindow::onNewTriggered);
    
          fileMenu->addAction(newAction);
          setMenuBar(menuBar);
      }

    private slots:
    void onNewTriggered() {
    QMessageBox::information(this, tr("Action Triggered"), tr("The 'New' action was triggered by a shortcut."));
    }
    };

    int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    MainWindow window;
    window.show();
    return app.exec();
    }

觉得有帮助的话,打赏一下呗。。

相关推荐
菜鸟看点8 小时前
自定义Cereal XML输出容器节点
c++·qt
漫步企鹅8 小时前
【蓝牙】Linux Qt4查看已经配对的蓝牙信息
linux·qt·蓝牙·配对
new_zhou9 小时前
Windows qt打包编译好的程序
开发语言·windows·qt·打包程序
看到我,请让我去学习17 小时前
Qt编程-qml操作(js,c++,canvas)
开发语言·qt
哈市雪花19 小时前
相机:Camera原理讲解(使用OpenGL+QT开发三维CAD)
qt·3d·交互·相机·图形学·opengl·视角
津津有味道21 小时前
Qt C++串口SerialPort通讯发送指令读写NFC M1卡
linux·c++·qt·串口通信·serial·m1·nfc
feiyangqingyun1 天前
全网唯一/Qt结合ffmpeg实现手机端采集摄像头推流到rtsp或rtmp/可切换前置后置摄像头/指定分辨率帧率
qt·智能手机·ffmpeg
随意0231 天前
Qt 事件
开发语言·qt
鸥梨菌Honevid1 天前
Qt自定义控件(1)——QPaintEvent
开发语言·qt
Mr_Xuhhh2 天前
网络基础(1)
c语言·开发语言·网络·c++·qt·算法