Qt学习笔记

1、常用控件

菜单栏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <QMenuBar>
#include <QMenu>
#include <QAction>
...
// 菜单栏
QMenuBar *mBar = menuBar();
// 添加菜单
QMenu *pFile = mBar->addMenu("文件");
// 菜单项和动作
QAction *pNew = pFile->addAction("新建");
connect(pNew, &QAction::triggered, [=]() {
qDebug() << "新建被触发";
});
pFile->addSeparator(); // 分割线
QAction *pOpen = pFile->addAction("打开");

工具栏

工具栏的实质是菜单栏的快捷方式

1
2
3
4
5
6
#include <QToolBar>
...
QToolBar *toolBar = addToolBar("toolBar");
toolBar->addAction(pNew);
QPushButton *qButton = new QPushButton(this);
toolBar->addWidget(qButton);

状态栏

1
2
3
4
5
6
7
8
#include <QStatusBar>
...
QStatusBar *sBar = statusBar();
QLabel *lable = new QLabel(this);
lable->setText("Normal");
sBar->addWidget(lable);
sBar->addWidget(new QLabel("2", this));
sBar->addPermanentWidget(new QLabel("3", this));

核心控件

核心控件有很多这里只是随便展示一种

1
2
3
4
#include <QTextEdit>
...
QTextEdit *textarea = new QTextEdit(this);
setCentralWidget(textarea);

浮动窗口

1
2
3
4
5
6
#include <QDockWidget>
...
QDockWidget *dw = new QDockWidget(this);
addDockWidget(Qt::RightDockWidgetArea, dw);
QTextEdit *textarea2 = new QTextEdit(this);
dw->setWidget(textarea2);

对话框

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
QMenuBar *mBar = menuBar();
setMenuBar(mBar);
QMenu *menu = mBar->addMenu("对话框");
QAction *p1 = menu->addAction("模态对话框");
connect(p1, &QAction::triggered, [=]() {
QDialog dlg;
dlg.exec();
qDebug() << "1";
});
QAction *p2 = menu->addAction("非模态对话框");
connect(p2, &QAction::triggered, [=]() {
QDialog *dlg = new QDialog;
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->show();
qDebug() << "2";
});
QAction *p3 = menu->addAction("关于对话框");
connect(p3, &QAction::triggered, [=]() {
QMessageBox::about(this, "关于", "Copyright 2016~2017");
});
QAction *p4 = menu->addAction("问题对话框");
connect(p4, &QAction::triggered, [=]() {
int ret = QMessageBox::question(this, "question", "Are you ok?");
switch (ret) {
case QMessageBox::Yes:
qDebug() << "I'm ok";
break;
case QMessageBox::No:
qDebug() << "I'm not ok";
break;
}
});
QAction *p5 = menu->addAction("文件对话框");
connect(p5, &QAction::triggered, [=]() {
QString path = QFileDialog::getOpenFileName(this, "open", "../",
"souce(*.cpp*.h);;Text(*.txt);;All(*.*)" );
qDebug() << path;
});
~感谢投食~