就像Swing里面的Action一样,Qt里面也有一个类似的类,叫做QAction。顾名思义,QAction类保存有关于这个动作,也就是action的信息,比如它的文本描述、图标、快捷键、回调函数(也就是信号槽),等等。神奇的是,QAction能够根据添加的位置来改变自己的样子——如果添加到菜单中,就会显示成一个菜单项;如果添加到工具条,就会显示成一个按钮。
代码如下:
//MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void openFile();
void add();
void remove();
private:
Ui::MainWindow *ui;
//QAction *openAcition;
QMenu *file;
QAction *addscess;
QToolBar *toolbar;
QToolBar *toolbar1;
};
#endif // MAINWINDOW_H
//MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QAction *openAcition = new QAction(tr("&Open"),this);
QAction *openAction = new QAction(tr("&apen"),this);
QAction *add = new QAction(tr("&add"),this);
QAction *remove = new QAction(tr("&remove"),this);
file = menuBar()->addMenu(tr("&File"));
file->addAction(openAcition);
file->addAction(add);
file->addAction(remove);
toolbar = addToolBar(tr("&File"));
toolbar->addAction(openAcition);
toolbar->addAction(openAction);
toolbar1 = addToolBar(tr("&File"));
//toolbar1->addAction(openAcition);
toolbar1->addAction(openAction);
connect(openAcition,SIGNAL(triggered()),this,SLOT(openFile()));
connect(add,SIGNAL(triggered()),this,SLOT(add()));
connect(remove,SIGNAL(triggered()),this,SLOT(remove()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::openFile()
{
qDebug()<<"I did that!!";
}
void MainWindow::add()
{
addscess = new QAction(tr("&addscess"),this);
file->addAction(addscess);
toolbar->addAction(addscess);
}
void MainWindow::remove()
{
file->removeAction(addscess);
toolbar->removeAction(addscess);
}