“需求”分析:
①有响应的“动作/Action”,使用QAction实现,这里的响应为弹出一个“消息框”。
②该“Action”可以在菜单栏、工具栏上点击。
③鼠标停留在该“动作”上时,状态栏显示关于该“动作”相关提示信息。
说明:
使用QMainWindow来使用菜单栏、工具栏、状态栏时会比较方便,因此使用QMainWindow来演示实例。
技术细节:
设置快捷键
this->myAction->setShortcuts(QKeySequence::Print);
设置状态栏显示
this->myAction->setStatusTip("This is my action.");
设置菜单栏
this->ui->menuBar->addMenu("Menus")->addAction(myAction);设置工具栏
this->ui->mainToolBar->addAction(myAction);
-----------------------------------------------------------------------
以下是全部源代码:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include
#include
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void popMesaagebox();
private:
Ui::MainWindow *ui;
QAction *myAction;
};
#endif // MAINWINDOW_H-----------------------------------------------------------------------
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->resize(600,400);
this->setWindowIcon(QIcon("./1.png"));
this->myAction = new QAction(this);
this->myAction->setText("MyAction");
this->myAction->setIcon(QIcon("./1.png"));
this->myAction->setStatusTip("This is my action.");
this->myAction->setShortcuts(QKeySequence::Print);
connect(myAction,SIGNAL(triggered()),this,SLOT(popMesaagebox()));
this->ui->menuBar->addMenu("Menus")->addAction(myAction);
this->ui->mainToolBar->addAction(myAction);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::popMesaagebox()
{
QMessageBox m(this);
m.setWindowTitle("MyAction");
m.setText("This is a messagebox for my action.");
m.exec();
}-----------------------------------------------------------------------
main.cpp
#include
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}