在主窗口基础之上,添加菜单和工具栏等的动作。
// !!! 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
2
3
#ifndef MAINWINDOW_H
4
#define MAINWINDOW_H
5
6
#include <QMainWindow>
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
#endif
22
23
24
#include <QAction>
25
#include <QMenuBar>
26
#include <QMessageBox>
27
#include <QStatusBar>
28
#include <QToolBar>
29
30
#include "mainwindow.h"
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
}
附件列表
MainWindow添加动作.jpg
转载于:https://www.cnblogs.com/LyndonMario/p/9326270.html