首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Qt 學習之路 (12):QMainWindow 選單與工具列實作 — QAction 統一管理 UI 命令

     編輯:關於C語言

延續 QMainWindow 架構,本篇實作「開啟檔案」功能,引入 Qt 核心類別 QAction:封裝文字、圖示、快捷鍵、狀態列提示、訊號/槽連接,同一個 QAction 同時加入選單與工具列自動適配顯示(選單顯示文字、工具列顯示圖示按鈕)。

步驟 1:表頭檔宣告 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

步驟 2:建立與配置 QAction 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() {}

關鍵 API 解析

函式/屬性用途備註
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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved