Qt控件:交互控件

交互控件

1. QAction

##1. 1简介与API

QAction 是一个核心类,用于表示应用程序中的一个操作(如菜单项、工具栏按钮或快捷键触发的功能)。它将操作的逻辑与 UI 表现分离,使代码更易于维护和扩展。

核心功能

  1. 统一操作逻辑:一个 QAction 可同时关联到菜单、工具栏和快捷键,避免代码重复。
  2. 状态管理:支持启用 / 禁用、选中 / 未选中(如复选框菜单项)等状态。
  3. 图标与文本:可设置图标、文本、工具提示等 UI 属性。
  4. 信号与槽:通过 triggered() 信号触发操作。

API

常用构造函数

cpp 复制代码
QAction(const QString &text, QObject *parent = nullptr);
QAction(const QIcon &icon, const QString &text, QObject *parent = nullptr);

设置属性

cpp 复制代码
setText(const QString &text):设置显示文本。
setIcon(const QIcon &icon):设置图标。
setToolTip(const QString &tip):设置工具提示。
setShortcut(const QKeySequence &shortcut):设置快捷键。
setCheckable(bool checkable):设置是否可勾选(如复选框菜单项)。
setChecked(bool checked):设置勾选状态。
setEnabled(bool enabled):启用 / 禁用操作。

获取属性

cpp 复制代码
text():获取显示文本。
icon():获取图标。
shortcut():获取快捷键。
isChecked():判断是否被勾选。
isEnabled():判断是否启用。

信号

cpp 复制代码
triggered():操作被触发时发出(如点击菜单项)。
toggled(bool checked):状态切换时发出(仅在 checkable 为 true 时)。

1.2 实例

应用情况

创建可勾选的动作(如工具栏按钮)

cpp 复制代码
QAction *toggleToolbarAction = new QAction("Show Toolbar", this);
toggleToolbarAction->setCheckable(true);
toggleToolbarAction->setChecked(true);  // 默认显示

connect(toggleToolbarAction, &QAction::toggled, [=](bool checked) {
    toolbar->setVisible(checked);
});

使用标准动作(如复制、粘贴)

cpp 复制代码
// 使用 Qt 预定义的标准动作
QAction *copyAction = new QAction(QIcon::fromTheme("edit-copy"), "Copy", this);
copyAction->setShortcut(QKeySequence::Copy);  // 自动适配平台(Ctrl+C 或 Command+C)
connect(copyAction, &QAction::triggered, textEdit, &QTextEdit::copy);

应用场景

cpp 复制代码
//菜单
QMenu *fileMenu = menuBar()->addMenu("File");
fileMenu->addAction(openAction);
fileMenu->addAction(saveAction);
fileMenu->addSeparator();  // 添加分隔线
fileMenu->addAction(exitAction);

//工具栏
QToolBar *toolbar = addToolBar("Main Toolbar");
toolbar->addAction(openAction);
toolbar->addAction(saveAction);

//快捷键
saveAction->setShortcut(QKeySequence("Ctrl+S"));
// 或使用标准快捷键
saveAction->setShortcut(QKeySequence::Save);

Qt 提供了许多预定义的标准快捷键,常见的包括:

常量 描述 Windows/Linux macOS
QKeySequence::Open 打开文件 Ctrl+O Command+O
QKeySequence::Save 保存文件 Ctrl+S Command+S
QKeySequence::Copy 复制 Ctrl+C Command+C
QKeySequence::Paste 粘贴 Ctrl+V Command+V
QKeySequence::Cut 剪切 Ctrl+X Command+X
QKeySequence::Undo 撤销 Ctrl+Z Command+Z
QKeySequence::Redo 重做 Ctrl+Y Command+Shift+Z
QKeySequence::Find 查找 Ctrl+F Command+F
QKeySequence::Quit 退出应用 Ctrl+Q Command+Q
相关推荐
Felix_One1 天前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端
norlan_jame9 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054969 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月9 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237179 天前
C语言-数组练习进阶
c语言·开发语言·算法