延續 QMainWindow 架構,本篇實作「開啟檔案」功能,引入 Qt 核心類別 QAction:封裝文字、圖示、快捷鍵、狀態列提示、訊號/槽連接,同一個 QAction 同時加入選單與工具列自動適配顯示(選單顯示文字、工具列顯示圖示按鈕)。
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui/QMainWindow>
class QAction; // 前向宣告
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private:
QAction *openAction; // 統一管理「開啟」命令
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include <QtGui/QAction>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QKeySequence>
#include <QtGui/QToolBar>
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// 1. 建立 QAction
openAction = new QAction(tr("&Open"), this);
openAction->setShortcut(QKeySequence::Open); // 標準快捷鍵 (跨平台自動對應)
openAction->setStatusTip(tr("Open a file.")); // 狀態列提示
// 2. 加入選單列
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAction);
// 3. 加入工具列
QToolBar *toolBar = addToolBar(tr("&File"));
toolBar->addAction(openAction);
}
MainWindow::~MainWindow() {}
| 函式/屬性 | 用途 | 備註 |
|---|---|---|
QAction(text, parent) | 建立動作 | parent 設為 this 利用 Qt 物件樹自動記憶體管理 |
setShortcut(QKeySequence::StandardKey) | 設定快捷鍵 | 使用標準鍵自動適配 Windows/Mac/Linux 鍵盤差異 |
setStatusTip() | 滑鼠懸停狀態列提示 | 需先 statusBar() 建立狀態列才會顯示 |
menuBar() | 取得/建立選單列 | 回傳 QMenuBar* |
addToolBar() | 建立並加入工具列 | 回傳 QToolBar* |
視窗頂端出現「檔案」選單與工具列,按 Alt+F 可鍵盤存取選單。目前點擊無反應,下篇將加入圖示與訊號/槽連接。
.cpp 中使用 QMenu、QMenuBar、QKeySequence、QToolBar 等類別,務必 #include 對應標頭檔,否則編譯失敗。
本文整理自「豆子空間」博客,原文出處:https://devbean.blog.51cto.com/448512/205034