Qt 使用QAction
類作為動作。這個動作可能顯示在菜單,作為一個菜單項,當用戶點擊該菜單項,對用戶的點擊做出響應;也可能在工具欄,作為一個工具欄按鈕,用戶點擊這個按鈕就可以執行相應的操作。
具體示例代碼:
1 // !!! Qt 5 2 // ========== mainwindow.h 3 #ifndef MAINWINDOW_H 4 #define MAINWINDOW_H 5 6 #include <QMainWindow> 7 8 class MainWindow : public QMainWindow 9 { 10 Q_OBJECT 11 public: 12 MainWindow(QWidget *parent = 0); 13 ~MainWindow(); 14 15 private: 16 void open(); 17 18 QAction *openAction; 19 }; 20 21 #endif // MAINWINDOW_H 22 23 // ========== mainwindow.cpp 24 #include <QAction> 25 #include <QMenuBar> 26 #include <QMessageBox> 27 #include <QStatusBar> 28 #include <QToolBar> 29 30 #include "mainwindow.h" 31 32 MainWindow::MainWindow(QWidget *parent) : 33 QMainWindow(parent) 34 { 35 setWindowTitle(tr("Main Window")); 36 37 openAction = new QAction(QIcon(":/images/doc-open"), tr("&Open..."), this); 38 openAction->setShortcuts(QKeySequence::Open); 39 openAction->setStatusTip(tr("Open an existing file")); 40 connect(openAction, &QAction::triggered, this, &MainWindow::open); 41 42 QMenu *file = menuBar()->addMenu(tr("&File")); 43 file->addAction(openAction); 44 45 QToolBar *toolBar = addToolBar(tr("&File")); 46 toolBar->addAction(openAction); 47 48 statusBar() ; 49 } 50 51 MainWindow::~MainWindow() 52 { 53 } 54 55 void MainWindow::open() 56 { 57 QMessageBox::information(this, tr("Information"), tr("Open")); 58 }
main函數:
1 #include "mainwindow.h" 2 #include <QApplication> 3 4 int main(int argc, char *argv[]) 5 { 6 QApplication app(argc, argv); 7 8 MainWindow win; 9 win.show(); 10 11 return app.exec(); 12 }
第37行,我們在堆上創建了openAction
對象。在QAction
構造函數,我們傳入了一個圖標、一個文本和 this 指針。
openAction = new QAction(QIcon(":/images/doc-open"), tr("&Open..."), this);
圖標我們使用了QIcon
,傳入值是一個字符串,這個字符串對應於 Qt 資源文件中的一段路徑。(注:這個路徑在我的qt5.9.2中是不存在的,這導致了原來的地方沒有了圖標,不知道是不是由於版本差異導致與原作者不同。)
第38行,我們使用了setShortcut()
函數,用於說明這個QAction
的快捷鍵。
openAction->setShortcuts(QKeySequence::Open);
Qt 的QKeySequence
為我們定義了很多內置的快捷鍵,比如我們使用的 Open。你可以通過查閱 API 文檔獲得所有的快捷鍵列表。 這個與我們自己定義的有什么區別呢?簡單來說,我們完全可以自己定義一個tr("Ctrl+O")
來實現快捷鍵。原因在於,這是 Qt 跨平台性的體現。比如 PC 鍵盤和 Mac 鍵盤是不一樣的,一些鍵在 PC 鍵盤上有,而 Mac 鍵盤上可能並不存在,或者反之。使用QKeySequence
類來添加快捷鍵,會根據平台的不同來定義相應的快捷鍵。
39行,setStatusTip()則實現了當用戶鼠標滑過這個 action 時,會在主窗口下方的狀態欄顯示相應的提示。
openAction->setStatusTip(tr("Open an existing file"));
40行的connect()函數,將這個QAction
的triggered()
信號與MainWindow
類的open()
函數連接起來。當用戶點擊了這個QAction
時,會自動觸發MainWindow
的open()
函數。
connect(openAction, &QAction::triggered, this, &MainWindow::open);
42-43行:
QMenu *file = menuBar()->addMenu(tr("&File")); file->addAction(openAction);
向菜單欄添加了一個 File 菜單,並且把這個QAction
對象添加到這個菜單。
45-46行:
QToolBar *toolBar = addToolBar(tr("&File")); toolBar->addAction(openAction);
新增加了一個 File 工具欄,也把QAction
對象添加到了這個工具欄。
48行的statusBar()則是創建了一個狀態欄。
具體的內容可能會在后文學到。
原文:https://www.devbean.net/2012/08/qt-study-road-2-action/