在 Qt 开发中,消息盒子(QMessageBox 和 对话框(QDialog 是最常用的用户交互手段之一。除了使用 Qt 自带的标准消息框,你还可以自定义对话框,实现更复杂的交互需求。


📌 目录

  1. 标准消息盒子:QMessageBox
  2. 标准对话框:QDialog
  3. 自定义对话框实现步骤
  4. 自定义对话框示例代码
  5. 拓展功能建议(关闭按钮、回调等)
  6. 官方文档参考链接

1️⃣ 标准消息盒子 QMessageBox

Qt 提供了多个常用的静态方法来弹出提示框:

QMessageBox::information(this, "提示", "操作成功");
QMessageBox::warning(this, "警告", "数据格式有误");
QMessageBox::critical(this, "错误", "无法连接服务器");
QMessageBox::question(this, "确认", "确定删除该项?", QMessageBox::Yes | QMessageBox::No);

🔁 返回值处理:

auto reply = QMessageBox::question(this, "退出", "是否退出程序?",
                    QMessageBox::Yes | QMessageBox::No);

if (reply == QMessageBox::Yes) {
    QApplication::quit();
}

2️⃣ 标准对话框 QDialog

✅ 创建模态对话框

QDialog dlg(this);
dlg.setWindowTitle("对话框");
dlg.exec();  // 阻塞方式,直到关闭对话框

✅ 使用自定义布局

QDialog dlg(this);
QVBoxLayout *layout = new QVBoxLayout(&dlg);
layout->addWidget(new QLabel("欢迎使用Qt!"));
layout->addWidget(new QPushButton("关闭", &dlg));
dlg.exec();

3️⃣ 自定义对话框实现步骤

步骤一:创建新类,继承自 QDialog

可使用 Qt Creator 菜单:
File → New File or Project → Qt → Qt Designer Form Class → Dialog with Buttons Bottom

或手动写类继承:

class MyDialog : public QDialog {
    Q_OBJECT

public:
    explicit MyDialog(QWidget *parent = nullptr);

private:
    QLineEdit *input;
};

步骤二:定义界面布局和控件

MyDialog::MyDialog(QWidget *parent) : QDialog(parent) {
    QVBoxLayout *layout = new QVBoxLayout(this);
    input = new QLineEdit(this);
    QPushButton *okBtn = new QPushButton("确定", this);

    layout->addWidget(new QLabel("请输入你的名字:"));
    layout->addWidget(input);
    layout->addWidget(okBtn);

    connect(okBtn, &QPushButton::clicked, this, &QDialog::accept);
}

步骤三:在主窗口中调用

MyDialog dlg(this);
if (dlg.exec() == QDialog::Accepted) {
    QString name = dlg.getInput();
    qDebug() << "输入的名字:" << name;
}

4️⃣ 自定义对话框完整示例

// MyDialog.h
class MyDialog : public QDialog {
    Q_OBJECT

public:
    explicit MyDialog(QWidget *parent = nullptr);
    QString getInput();

private:
    QLineEdit *input;
};

// MyDialog.cpp
MyDialog::MyDialog(QWidget *parent) : QDialog(parent) {
    QVBoxLayout *layout = new QVBoxLayout(this);
    input = new QLineEdit(this);
    QPushButton *okBtn = new QPushButton("确定");

    layout->addWidget(new QLabel("请输入:"));
    layout->addWidget(input);
    layout->addWidget(okBtn);

    connect(okBtn, &QPushButton::clicked, this, &QDialog::accept);
}

QString MyDialog::getInput() {
    return input->text();
}

5️⃣ 拓展功能建议

功能实现方式
关闭按钮/取消增加 QPushButton("取消"),连接 reject()
回调函数使用信号槽机制(如发送 inputReady(QString)
美化UI设置 QSS 样式、调整边距、字体等
多字段表单多个 QLineEdit/QComboBox + 表单布局

🔗 6️⃣ 官方文档参考链接