【Qt】消息对话框 QMessageBox

消息对话框 QMessageBox

QMessageBox 用于显示一个消息给用户,,并且让用户进行一个简单的选择。

消息对话框是应⽤程序中最常⽤的界⾯元素。消息对话框主要⽤于为⽤⼾提⽰重要信息,强制⽤⼾进⾏选择操作。

例子:创建一个消息对话框

(1)在Qt Designer中设置一个按钮

(2)右键点击按钮,转到槽,编辑点击按钮的槽函数

(3)创建消息对话框QMessageBox,并设置对话框标题与对话框文本

(4)设置图标

QMessageBox类 中定义了静态成员函数,可以直接调⽤创建不同⻛格的消息对话框,其中包括:

Question
⽤于正常操作过程中的提问
Information
⽤于报告正常运⾏信息
Warning
⽤于报告⾮关键错误
Critical
⽤于报告严重错误

(4)设置标准选项按钮

(5)设置模态对话框

(6)运行程序

(7)代码展示

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    // 创建出一个消息对话框
    QMessageBox* messageBox = new QMessageBox(this);
    // 设置对话框标题
    messageBox->setWindowTitle("消息对话框");
    // 设置对话框文本
    messageBox->setText("消息对话框文本");

    // 设置图标
    messageBox->setIcon(QMessageBox::Information);

    // 设置选项按钮
    messageBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Save | QMessageBox::Cancel);

    // 设置模态对话框
    messageBox->exec();
}

例子:在QMessageBox设置自定义按钮

(1)在上述例子中,取消使用标准定义的按钮,设置自定义按钮

该函数提供的俩个参数,一个是button抽象类,一个是button所起到的作用。

(2)使用自定义按钮,可以使用connect连接信号槽,来针对当前点击的按钮进行一些相关操作。

(3)标准规定的按钮中,没法进行信号槽的连接

用户点击按钮,是对话框关闭之后,此时可以通过获取 exec 的返回值,来了解用户点击的是哪一个按钮,从而执行一些逻辑。

(4)代码展示

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QPushButton>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    // 创建出一个消息对话框
    QMessageBox* messageBox = new QMessageBox(this);
    // 设置对话框标题
    messageBox->setWindowTitle("消息对话框");
    // 设置对话框文本
    messageBox->setText("消息对话框文本");

    // 设置图标
    messageBox->setIcon(QMessageBox::Information);

    // 设置选项按钮
     messageBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Save | QMessageBox::Cancel);
//    QPushButton* button = new QPushButton("按钮");
//    messageBox->addButton(button, QMessageBox::AcceptRole);
//    connect(button, &QPushButton::clicked, this, &MainWindow::handle);

    // 设置模态对话框
    int reslut = messageBox->exec();
    if(reslut == QMessageBox::Ok)
    {
        qDebug() << "Ok";
    }
    else if(reslut == QMessageBox::Save)
    {
        qDebug() << "Save";
    }
    else if(reslut == QMessageBox::Cancel)
    {
        qDebug() << "Cancel";
    }
}

void MainWindow::handle()
{
    qDebug() << "button";
}

例子:快捷创建消息对话框

(1)在Qt Designer中创建一个按钮

(2)编辑点击按钮的槽函数

(3)快捷创建消息对话框

查看该函数的四个参数: 

(4)获取该函数的返回值,并进行判定

(5)执行程序

评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值