一、QAction
一、QAction的例子
main.cpp
#include "test.h"
#include <QtWidgets/QApplication>
#include<qpushbutton.h>
#include<qapplication.h>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TEST win;
win.show();
return app.exec();
}
test.h
#ifndef TEST_H
#define TEST_H
#include <QtWidgets/QMainWindow>
#include "ui_test.h"
class TEST : public QMainWindow
{
Q_OBJECT
public:
TEST(QWidget *parent = 0);
~TEST();
private:
void open();
QAction *openAction;
};
#endif // TEST_H
test.cpp
#include "test.h"
#include <QAction>
#include <QMenuBar>
#include <QMessageBox>
#include <QStatusBar>
#include <QToolBar>
TEST::TEST(QWidget *parent)
: QMainWindow(parent)
{
setWindowTitle(tr("First Main Window"));
openAction = new QAction(QIcon(":/images/doc-open"), tr("&Open..."), this);
openAction->setShortcuts(QKeySequence::Open);
openAction->setStatusTip(tr("Open an existing file"));
connect(openAction, &QAction::triggered, this, &TEST::open);//當有triggered()信號發出時觸發槽函數open()
QMenu *file = menuBar()->addMenu(tr("&File"));
file->addAction(openAction);
QToolBar *toolBar = addToolBar(tr("&File"));
toolBar->addAction(openAction);
statusBar();
}
TEST::~TEST()
{
}
void TEST::open()
{
QMessageBox::information(this, tr("Information"), tr("Open"));
}
效果如圖:
二、對於代碼的解讀
1)test.h
在test.h中我們聲明瞭TEST類中:
a、私有函數open()
b、私有指針openAction,指向一個QAcion型數據
2)test.cpp
a、setWindowTitle() 設置title內容,tr()爲規範化
b、QAction類的構造函數解析:
openAction = new QAction(QIcon(":/images/doc-open"), tr("&Open..."), this);
第一參數:圖標
QIcon():輸入爲一個路徑,函數找到了這裏的 document-open.png 圖標
第二參數:爲action的名稱
從效果圖上能看出對應的位置,需要注意的是文本前的”&”符號,意味着有設定了快捷鍵,在緊接着調用的setShortcut()函數就是設置快捷鍵。
第三參數:this指針
c、other
menuBar()、toolBar()和statusBar()三個是QMainWindow的函數,用於創建並返回菜單欄、工具欄和狀態欄。我們可以從代碼清楚地看出,我們向菜單欄添加了一個 File 菜單,並且把這個QAction對象添加到這個菜單;同時新增加了一個 File 工具欄,也把QAction對象添加到了這個工具欄。我們可以看到,在菜單中,這個對象被顯示成一個菜單項,在工具欄變成了一個按鈕。至於狀態欄,則是出現在窗口最下方,用於顯示動作對象的提示信息的。