目录
  1. 1. 菜单栏、工具栏和状态栏
Qt学习笔记-4 菜单栏、工具栏和状态栏

菜单栏、工具栏和状态栏

Qt 将用户与界面进行交互的元素抽象为一种“动作”,使用QAction类表示。QAction可以添加到菜单上、工具栏上。

我们假设窗口还是建立在QMainWindow类之上,这会让我们的开发简单许多。当然,在实际开发过程中,QMainWindow通常只作为“主窗口”,对话框窗口则更多地使用QDialog类。我们会在后面看到,QDialog类会缺少一些QMainWindow类提供方便的函数,比如menuBar()以及toolBar()

在添加动作这一代码中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// !!! Qt 5
// ========== mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();

private:
void open();

QAction *openAction;
};

#endif // MAINWINDOW_H

// ========== mainwindow.cpp
#include <QAction>
#include <QMenuBar>
#include <QMessageBox>
#include <QStatusBar>
#include <QToolBar>

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
setWindowTitle(tr("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, &MainWindow::open);

QMenu *file = menuBar()->addMenu(tr("&File"));
file->addAction(openAction);

QToolBar *toolBar = addToolBar(tr("&File"));
toolBar->addAction(openAction);

statusBar() ;
}

MainWindow::~MainWindow()
{
}

void MainWindow::open()
{
QMessageBox::information(this, tr("Information"), tr("Open"));
}

看以下代码片段

1
2
3
4
5
6
7
8
9
10
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, MainWindow::open);

QMenu *file = menuBar()->addMenu(tr("&File"));
file->addAction(openAction);

QToolBar *toolBar = addToolBar(tr("&File"));
toolBar->addAction(openAction);

我们看到menuBar()函数,Qt为我们创建了一个菜单栏。menuBar()QMainWindow提供的函数,因此你是不会在QWidget或者QDialog中找到它的。这个函数会返回窗口的菜单栏,如果没有菜单栏则会新创建一个。这也就解释了,为什么我们可以直接使用menuBar()函数的返回值,毕竟我们并没有创建一个菜单栏对象啊!原来,这就是menuBar()为我们创建好并且返回了的。

Qt 中,表示菜单的类是QMenuBar(你应该已经想到这个名字了)。QMenuBar代表的是窗口最上方的一条菜单栏。我们使用其addMenu()函数为其添加菜单。尽管我们只是提供了一个字符串作为参数,但是 Qt 为将其作为新创建的菜单的文本显示出来。至于 & 符号,我们已经解释过,这可以为菜单创建一个快捷键。当我们创建出来了菜单对象时,就可以把QAction添加到这个菜单上面,也就是addAction()函数的作用。
下面的QToolBar部分非常类似。顾名思义,QToolBar就是工具栏。我们使用的是addToolBar()函数添加新的工具栏。为什么前面一个是menuBar()而现在的是addToolBar()呢?因为一个窗口只有一个菜单栏,但是却可能有多个工具栏。如果我们将代码修改一下:

1
2
3
4
5
QToolBar *toolBar = addToolBar(tr("&File"));
toolBar->addAction(openAction);

QToolBar *toolBar2 = addToolBar(tr("Tool Bar 2"));
toolBar2->addAction(openAction);
文章作者: XyLan
文章链接: https://blog.xylan.cn/2023/04/26/Qt%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-4%20%E8%8F%9C%E5%8D%95%E6%A0%8F%E3%80%81%E5%B7%A5%E5%85%B7%E6%A0%8F%E5%92%8C%E7%8A%B6%E6%80%81%E6%A0%8F/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 XyLan
打赏
  • 微信
  • 支付寶