qt弹窗

独立弹窗

main.cpp

1
2
3
4
5
6
7
8
9
10
11
#include <QApplication>
#include <QMessageBox>

int main(int argc, char *argv[]) {
QApplication a(argc, argv);

// parent 传 nullptr,弹窗将作为一个独立的顶级窗口出现在屏幕中央
QMessageBox::information(nullptr, "系统提示", "检测到环境异常,程序将退出。");

return 0; // 弹窗关闭后直接结束程序
}

窗口弹窗

main.cpp

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <QApplication>
#include <QMessageBox>
#include <QInputDialog>
#include <QFileDialog>
#include <QColorDialog>
#include <QDialog>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QDebug>

// --- A. 基础提示类 (QMessageBox) ---
void testStandardMessage(QWidget *parent) {
// 1. 简单信息提示
QMessageBox::information(parent, "提示", "操作已成功完成!");

// 2. 带逻辑判断的询问
auto result = QMessageBox::question(parent, "确认", "你确定要执行此操作吗?",
QMessageBox::Yes | QMessageBox::No);
if (result == QMessageBox::Yes) {
qDebug() << "用户点击了确定";
}
}

// --- B. 输入类 (QInputDialog) ---
void testInputForms(QWidget *parent) {
bool ok;
// 获取字符串输入
QString text = QInputDialog::getText(parent, "输入框", "请输入你的名字:",
QLineEdit::Normal, "默认值", &ok);
if (ok && !text.isEmpty()) {
qDebug() << "获取到输入:" << text;
}
}

// --- C. 系统资源类 (QFileDialog/QColorDialog) ---
void testSystemDialogs(QWidget *parent) {
// 1. 选择文件
QString fileName = QFileDialog::getOpenFileName(parent, "选择图片", "/", "Images (*.png *.jpg)");
if (!fileName.isEmpty()) qDebug() << "选择的文件路径:" << fileName;

// 2. 选择颜色
QColor color = QColorDialog::getColor(Qt::white, parent, "选择背景颜色");
if (color.isValid()) qDebug() << "选择的颜色是:" << color.name();
}

// --- D. 自定义复杂弹窗 (继承 QDialog) ---
void testCustomDialog(QWidget *parent) {
// 这种通常用于登录、设置等复杂场景
QDialog dlg(parent);
dlg.setWindowTitle("自定义登录弹窗");

QVBoxLayout *layout = new QVBoxLayout(&dlg);
layout->addWidget(new QLabel("用户名:"));
QLineEdit *nameInput = new QLineEdit(&dlg);
layout->addWidget(nameInput);

QPushButton *btn = new QPushButton("确认", &dlg);
layout->addWidget(btn);

// 点击按钮关闭弹窗并返回“接受”状态
QObject::connect(btn, &QPushButton::clicked, &dlg, &QDialog::accept);

if (dlg.exec() == QDialog::Accepted) {
qDebug() << "登录名称:" << nameInput->text();
}
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);

// 创建一个空的父窗口,使弹窗居中显示
QWidget w;
w.show();

// --- 调用测试函数 ---

// testStandardMessage(&w); // 测试信息提示
//testInputForms(&w); // 测试输入框
// testSystemDialogs(&w); // 测试文件和颜色选择
testCustomDialog(&w); // 测试自定义弹窗

return a.exec();
}