Qt 使用QAction
类作为动作,QAction
包含了图标、菜单文字、快捷键、状态栏文字、浮动帮助等信息,Qt自己选择使用哪个属性来显示,无需我们关心。同时,Qt 能够保证把QAction
对象添加到不同的菜单、工具栏时,显示内容是同步的。也就是说,如果我们在菜单中修改了QAction
的图标,那么在工具栏上面这个QAction
所对应的按钮的图标也会同步修改。
#include "mainwindow.h"
#include <QIcon>
#include <QAction>
#include <QMenuBar>
#include <QMessageBox>
#include <QToolBar>
#include <QStatusBar>
#include <iterator>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
CreateQButton();
}
MainWindow::~MainWindow()
{
if(openAction) delete openAction;
}
void MainWindow::CreateQButton()
{
setWindowTitle(tr("Main Window"));
openAction = new QAction(QIcon(), "打开...", this);//new 了之后要释放内存(delete),不然会造成内存泄漏
openAction->setShortcuts(QKeySequence::Open);//说明这个QAction的快捷键Ctrl+O,也可以自定义
openAction->setStatusTip(tr("Open an existing file"));//etStatusTip()实现了当用户鼠标滑过这个 action 时,会在主窗口下方的状态栏显示相应的提示
connect(openAction, &QAction::triggered, this, &MainWindow::open);
QMenu *file = menuBar()->addMenu("文件");
file->addAction(openAction);
QToolBar *toolBar = addToolBar("SSS");
toolBar->addAction(openAction);
QStatusBar *statBar = statusBar();
statBar->addAction(openAction);
}
void MainWindow::open()
{
QMessageBox::information(this, tr("信息"), tr("功能暂未实现"));
}