6.添加动作
在主窗口基础之上,添加菜单和工具栏等的动作。
// !!! 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"));
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow win;
win.show();
return app.exec();
}
x
58
1
// !!! Qt 5
2
// ========== mainwindow.h
3
4
5
6
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
// MAINWINDOW_H
22
23
// ========== mainwindow.cpp
24
25
26
27
28
29
30
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
}
59
60
61
int main(int argc, char *argv[])
62
{
63
QApplication app(argc, argv);
64
65
MainWindow win;
66
win.show();
67
68
return app.exec();
69
}