卖不甜枣 发表于 2024-11-1 15:27:41

qt QAction详解

1、概述

QAction是Qt框架中的一个抽象类,用于表示用户界面中的一个动作(action)。这些动作可以绑定到菜单项、工具栏按钮或快捷键上,提供了一种机动的方式来处置惩罚用户交互。QAction不仅包含了动作的名称、图标、提示信息等属性,还可以与特定的回调函数关联,当动作被触发时,执行相应的回调函数。
QAction是Qt信号与槽机制的一个典型应用,它允许开辟职员将动作与用户界面元素解耦,从而更轻易地管理和维护代码。通过使用QAction,开辟职员可以创建一致的、可重用的用户界面元素,提拔应用步伐的可维护性和用户体验。
2、重要方法



[*]setText(const QString &text):设置动作的文本标签。
[*]setIcon(const QIcon &icon):设置动作的图标。
[*]setShortcut(const QKeySequence &shortcut):设置动作的快捷键。
[*]setStatusTip(const QString &statusTip):设置动作的状态提示信息,通常表现在状态栏中。
[*]setToolTip(const QString &tip):设置动作的工具提示信息,当用户将鼠标悬停在动作上时表现。
[*]setWhatsThis(const QString &text):设置动作的“这是什么”资助信息,当用户按下Shift+F1并悬停在动作上时表现。
[*]triggered(bool checked = false):这是一个信号,当动作被触发时发出。在子类中可以重写此方法以提供自界说行为。
[*]connect():通常与triggered信号一起使用,将动作与特定的回调函数关联。

3、重要信号



[*]triggered(bool checked = false):当动作被触发时发出此信号。假如动作是可检查的(checkable),则checked参数指示动作是否被选中。
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QToolBar>
#include <QAction>
#include <QMessageBox>

class MainWindow : public QMainWindow {
    Q_OBJECT

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

      // 创建动作
      QAction *newAction = new QAction(tr("&New"), this);
      newAction->setIcon(QIcon(":/icons/new.png"));
      newAction->setStatusTip(tr("Create a new file"));
      connect(newAction, &QAction::triggered, this, &MainWindow::onNewFile);

      QAction *openAction = new QAction(tr("&Open..."), this);
      openAction->setIcon(QIcon(":/icons/open.png"));
      openAction->setStatusTip(tr("Open an existing file"));
      connect(openAction, &QAction::triggered, this, &MainWindow::onOpenFile);

      // 将动作添加到菜单
      fileMenu->addAction(newAction);
      fileMenu->addAction(openAction);

      // 创建工具栏
      QToolBar *toolBar = this->addToolBar(tr("Main Toolbar"));
      toolBar->addAction(newAction);
      toolBar->addAction(openAction);
    }

private slots:
    void onNewFile() {
      QMessageBox::information(this, tr("New File"), tr("Create a new file..."));
    }

    void onOpenFile() {
      QMessageBox::information(this, tr("Open File"), tr("Open an existing file..."));
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    MainWindow window;
    window.show();

    return app.exec();
}
https://i-blog.csdnimg.cn/direct/04d2391f86d5413aa7e819679cecc251.gif
https://i-blog.csdnimg.cn/direct/2c0529c4ab15486da4ded1bcb95ae5ca.png
以为有资助的话,打赏一下呗。。
https://i-blog.csdnimg.cn/blog_migrate/9d04eaa4169a3fa73687a27d256882f1.jpeg           https://i-blog.csdnimg.cn/blog_migrate/45f5aa2e88f147453c0764b3e7543f63.jpeg

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: qt QAction详解