Qt-QMainWindow

Qt-QMainWindow

QMainWindow是一個提供主窗口程序的類,窗口包含以下部分

  • 一個菜單欄(menu bar)
  • 多個工具欄(tool bars)
  • 多個錨接部件(dock widgets)
  • 一個狀態欄(status bar)
  • 一箇中心部件(central widget)
    這裏寫圖片描述

菜單欄

菜單欄的每一個menu都可以用menuBar()的addMenu()添加

fileMenu = menuBar()->addMenu("file"); //創建了file菜單

QAction

可以將QAction對象添加到菜單欄的菜單裏面和下面要講到的工具欄裏面,這樣一旦用戶選擇了這個操作,QAction的triggered(bool) 就會發出信號。圖中工具欄裏的各個工具均爲QAction對象,可以爲QAction 對象添加圖標以及快捷鍵等。

QAction *fileOpenAction = QAction(QIcon("open.png"), "open", this);
fileOpenAction->setShortcut(tr("Ctrl+O"));
fileOpenAction->setStatusTip("Open a file");
fileMenu->addAction(fileOpenAction);
fileMenu->addSeparator(); //可以添加分隔符

這樣就會在菜單欄的file菜單下出現一個圖標爲open.png名字爲open的選項,然後就可以用connect設置相關操作

工具欄

可以用addToolBar()添加一個工具條

QToolBar *fileBar = addToolBar("file");
fileBar->addAction(fileOpenAction);

工具條裏不光能放QAction對象,還可以放其它的widget

狀態欄

用statusBar()->addWidget()添加狀態欄項

QLabel *statusLabel = new QLabel("status");
statusBar()->addWidget(statusLabel);

使用槽函數顯示信息,timeout單位是毫秒

//void showMessage(const QString &message, int timeout = 0) 

中心部件

一個主窗口只有一箇中心部件,可以用setCentralWidget()設定

代碼

以下代碼頭文件已省略

//mainwindow.h
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    QTextEdit *mainEdit;
    QTextEdit *sideEdit;
    QAction *fileOpenAction;
    QLabel *statusLabel;
    QMenu *fileMenu;
    QToolBar *fileToolBar;
    QHBoxLayout *mainLayout;

private slots:
    void showOpenFile();
};
//mainwindow.cpp
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle("MainWindow");

    //添加QAction
    fileOpenAction = new QAction("open", this);
    fileOpenAction->setShortcut(QString("Ctrl+O"));
    fileOpenAction->setToolTip("open a new file");
    connect(fileOpenAction, SIGNAL(triggered(bool)), this, SLOT(showOpenFile()));

    //添加菜單
    fileMenu = menuBar()->addMenu("file");
    fileMenu->addAction(fileOpenAction);

    //添加工具欄
    fileToolBar = addToolBar("file");
    fileToolBar->addAction(fileOpenAction);

    //設置中心部件
    mainEdit = new QTextEdit;
    setCentralWidget(mainEdit);

    //設置狀態欄
    statusLabel = new QLabel;
}

MainWindow::~MainWindow()
{

}

void MainWindow::showOpenFile()
{
    statusBar()->showMessage("hello", 3000);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章