1. QMessageBox原有的弹窗

  QMessageBox messageBox(QMessageBox::Question, "提示", "是否保存当前项目?", QMessageBox::Yes | QMessageBox::No);
  messageBox.exec();

在这里插入图片描述
可以看出QMessageBox原有的弹窗看起来非常的不美观,有时候大有时候小,只能使用QMessageBox自带的图标,而且不能自定义窗口的大小,那是因为在源码中将其弹窗大小设置成了比较合适的大小,所以不能自定义改变弹窗大小,如下所示代码都是不起作用的:

   messageBox.setGeometry(800, 300, 450, 225);  //(500,300)设置其位置是有效的,但是设置其大小(450, 225)是无效的
   messageBox.resize(450, 225);                 //resize大小也是无效的

2. 网上第一种方法:通过样式表setStyleSheet实现改变弹窗大小(总体不美观)

  QMessageBox messageBox(QMessageBox::Question, "提示", "是否保存当前项目?", QMessageBox::Yes | QMessageBox::No);
  messageBox.setStyleSheet("QLabel{"
                             "min-width:150px;"
                             "min-height:120px;"
                             "font-size:16px;"
                             "}");
  messageBox.exec();

在这里插入图片描述
可以看出通过样式表的方法也不太美观,其中text没有居中。

3. 网上第二种方法:重写ShowEvent()改变弹窗大小(总体也不美观)

先上代码实现一下:
MyMessageBox.h

#include <QLabel>
#include <QMessageBox>
#include <QWidget>
class MyMessageBox : public QMessageBox {
    Q_OBJECT
public:
    MyMessageBox(Icon icon, const QString& title, const QString& text,
                 StandardButtons buttons, QWidget* parent = 0);
    ~MyMessageBox();
protected:
    void showEvent(QShowEvent* event) override;

MyMessageBox.cpp

#include "mymessagebox.h"
MyMessageBox::MyMessageBox(Icon icon, const QString& title, const QString& text,
                           StandardButtons buttons, QWidget* parent) :
    QMessageBox(icon, title, text, buttons, parent) {
MyMessageBox::~MyMessageBox() {
void MyMessageBox::showEvent(QShowEvent* event) {
    QWidget* textLabel = findChild<QWidget*>("qt_msgbox_label");       //获取源码中text的label组件
    QWidget* iconLabel = findChild<QWidget*>("qt_msgbox_icon_label");  //获取源码中icon的label组件
    if (textLabel != nullptr) {  //使用指针之前先判断是否为空
        textLabel->setMinimumSize(450, 255);
        // textLabel->setFixedSize(450, 255);
    if (iconLabel != nullptr) {
        iconLabel->setMinimumHeight(255);
        iconLabel->setFixedSize(450, 255);
    QMessageBox::showEvent(event);

main.cpp

#include <QApplication>
#include "mymessagebox.h"
int main(int argc, char* argv[]) {
    QApplication a(argc, argv);
    MyMessageBox messageBox(QMessageBox::Question, "提示", "是否保存当前项目?", QMessageBox::Yes | QMessageBox::No);
    messageBox.exec();
    //w.show();
    return a.exec();

解释一下上面的一些代码
先看一下QMessageBox中的一些源码:
在这里插入图片描述
在对某一个组件设置了setObjectName()属性之后,我们可以通过objectName在外面获得这个组件,如下:

//QLabel继承于QWidget,所以用QWidget*是可以的
QWidget* textLabel = findChild<QWidget*>("qt_msgbox_label");  //获取源码中text的label组件

然后对label组件的大小进行调整,达到调整弹窗大小的目的。可以看到弹窗的大小是改变了,但是还是不美观,主要是图标没有居中,还是处在左上角的位置,如下图所示:

在这里插入图片描述
那对于上面这个问题出现的原因是什么呢?那就看一下QMessageBox中的关于布局Layout的一些源码:
在这里插入图片描述
可以看出在布局时,其icon总是处在第0行第0列的位置,且其Aliment设置的是Top,所以导致了QMessageBox的图标总是在左上角。
所以重写ShowEvent()这种方法也达不到实现美观的弹窗的预期。

4. 最好的办法:继承QDialog重新实现弹窗界面(附完整代码)(v1.0)

重新写一个弹窗TipDialog类,继承于QDialog类。
先看效果:
在这里插入图片描述
直接上代码:
TipDialog.h

#ifndef TIPDIALOG_H
#define TIPDIALOG_H
#include <QDialog>
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
#include <QMessageBox>
#include <QMetaEnum>
#include <QPixmap>
#include <QPushButton>
#include <QVBoxLayout>
class TipDialog : public QDialog {
    Q_OBJECT
public:
    enum TipIcon {
        NoIcon = 0,
        Information = 1,
        Question = 2,
        Success = 3,
        Warning = 4,
        Critical = 5
    Q_ENUM(TipIcon)  //使用Q_ENUM注册枚举
    enum StandardButton {
        //保持与 QDialogButtonBox::StandardButton 一致,后面在创建按钮时会用到 & 运算
        NoButton = 0x00000000,
        Ok = 0x00000400,
        Save = 0x00000800,
        SaveAll = 0x00001000,
        Open = 0x00002000,
        Yes = 0x00004000,
        YesToAll = 0x00008000,
        No = 0x00010000,
        NoToAll = 0x00020000,
        Abort = 0x00040000,
        Retry = 0x00080000,
        Ignore = 0x00100000,
        Close = 0x00200000,
        Cancel = 0x00400000,
        Discard = 0x00800000,
        Help = 0x01000000,
        Apply = 0x02000000,
        Reset = 0x04000000,
        RestoreDefaults = 0x08000000,
        FirstButton = Ok,
        LastButton = RestoreDefaults
    Q_ENUM(StandardButton)
    Q_DECLARE_FLAGS(StandardButtons, StandardButton)
    Q_FLAG(StandardButtons)
    enum ButtonRole {
        //保持与 QDialogButtonBox::ButtonRole 一致
        InvalidRole = -1,
        AcceptRole,
        RejectRole,
        DestructiveRole,
        ActionRole,
        HelpRole,
        YesRole,
        NoRole,
        ResetRole,
        ApplyRole,
        NRoles
    explicit TipDialog(QWidget* parent = nullptr);
    TipDialog(TipIcon icon, const QString& title, const QString& text, StandardButtons buttons,
              QWidget* parent = nullptr);  //构造函数有默认值的要放后面
    ~TipDialog();
    static void information(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons = Ok);
    static void question(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons = StandardButtons(Yes | No));
    static void success(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons = Ok);
    static void warning(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons = Ok);
    static void critical(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons = Ok);
private:
    void init(const QString& title = QString(), const QString& text = QString());
    void setupLayout();
    QPixmap standardIcon(TipDialog::TipIcon icon);
    void setIcon(TipIcon icon);
    void createButton(StandardButton button);
    void createStandardButtons(StandardButtons buttons);
    void setStandardButtons(StandardButtons buttons);
    //    QString standardTitle(TipDialog::TipIcon icon);
    QString getEnumKey(StandardButton button);
    void addButton(StandardButton button, QDialogButtonBox::ButtonRole buttonRole);
private:
    QLabel* m_pIconLabel;
    QLabel* m_pTextLabel;
    QDialogButtonBox* m_pButtonBox;
    //    QList<QPushButton*> m_pButtonList;
    QString m_text;
//在全局任意地方使用"|"操作符计算自定义的枚举量,需要使用Q_DECLARE_OPERATORS_FOR_FLAGS宏
Q_DECLARE_OPERATORS_FOR_FLAGS(TipDialog::StandardButtons)
#endif  // TIPDIALOG_H

TipDialog.cpp

#include "tipdialog.h"
#define fontFamily "宋体"
#define fontSize 12
TipDialog::TipDialog(QWidget* parent) :
    QDialog(parent) {
    init();
TipDialog::TipDialog(TipIcon icon, const QString& title, const QString& text, StandardButtons buttons, QWidget* parent) :
    QDialog(parent) {
    init(title, text);
    setWindowTitle(title);
    setIcon(icon);
    setStandardButtons(buttons);
    //    setupLayout();
TipDialog::~TipDialog() {}
void TipDialog::information(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons) {
    TipDialog tip(Information, title, text, buttons, parent);
    tip.exec();
void TipDialog::question(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons) {
    TipDialog tip(Question, title, text, buttons, parent);
    tip.exec();
void TipDialog::success(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons) {
    TipDialog tip(Success, title, text, buttons, parent);
    tip.exec();
void TipDialog::warning(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons) {
    TipDialog tip(Warning, title, text, buttons, parent);
    tip.exec();
void TipDialog::critical(QWidget* parent, const QString& title, const QString& text, StandardButtons buttons) {
    TipDialog tip(Critical, title, text, buttons, parent);
    tip.exec();
void TipDialog::init(const QString& title, const QString& text) {
    resize(QSize(450, 225));
    setWindowIcon(QIcon(":/new/prefix1/Icon/项目.png"));
    setWindowTitle("operation tip...");
    setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);  //设置右上角按钮
    //setAttribute(Qt::WA_DeleteOnClose);                                   //关闭窗口时将窗口释放掉即释放内存
    m_pIconLabel = new QLabel(this);
    m_pIconLabel->setObjectName(QLatin1String("iconLabel"));
    m_pTextLabel = new QLabel(this);
    m_pTextLabel->setObjectName(QLatin1String("textLabel"));
    m_pTextLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);  //label中的内容可用鼠标选择文本复制,链接激活
    m_pTextLabel->setOpenExternalLinks(true);                           //label中的内容若为链接,可直接点击打开
    m_pButtonBox = new QDialogButtonBox(this);
    m_pButtonBox->setObjectName(QLatin1String("buttonBox"));
    if (!title.isEmpty() || !text.isEmpty()) {
        setWindowTitle(title);
        m_pTextLabel->setFont(QFont(fontFamily, fontSize));
        m_pTextLabel->setText(text);
    m_text = text;
    setupLayout();
void TipDialog::setupLayout() {
    QHBoxLayout* HLay = new QHBoxLayout;
    HLay->addWidget(m_pIconLabel, 1, Qt::AlignVCenter | Qt::AlignRight);
    HLay->addWidget(m_pTextLabel, 5, Qt::AlignCenter);
    QVBoxLayout* VLay = new QVBoxLayout;
    VLay->addLayout(HLay);
    VLay->addWidget(m_pButtonBox);
    setLayout(VLay);
QPixmap TipDialog::standardIcon(TipDialog::TipIcon icon) {
    QPixmap pixmap;
    switch (icon) {
        case TipDialog::Information:
            pixmap.load(":/new/prefix1/Image/Information.png");
            break;
        case TipDialog::Question:
            pixmap.load(":/new/prefix1/Image/Question.png");
            break;
        case TipDialog::Success:
            pixmap.load(":/new/prefix1/Image/Success.png");
            break;
        case TipDialog::Warning:
            pixmap.load(":/new/prefix1/Image/Warning.png");
            break;
        case TipDialog::Critical:
            pixmap.load(":/new/prefix1/Image/Critical.png");
            break;
        default:
            break;
    if (!pixmap.isNull())
        return pixmap;
    return QPixmap();
void TipDialog::setIcon(TipDialog::TipIcon icon) {
    m_pIconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    m_pIconLabel->setPixmap(standardIcon(icon));
void TipDialog::createButton(StandardButton button) {
    switch (button) {
        case TipDialog::Ok:
            addButton(button, QDialogButtonBox::AcceptRole);
            break;
        case TipDialog::Save:
            addButton(button, QDialogButtonBox::AcceptRole);
            break;
        case TipDialog::Yes:
            addButton(button, QDialogButtonBox::YesRole);
            break;
        case TipDialog::No:
            addButton(button, QDialogButtonBox::NoRole);
            break;
        case TipDialog::Cancel:
            addButton(button, QDialogButtonBox::RejectRole);
            break;
        default:
            break;
void TipDialog::createStandardButtons(StandardButtons buttons) {
    //TipDialog::StandardButtons 与 QDialogButtonBox::StandardButtons 的枚举是一样的
    uint i = QDialogButtonBox::FirstButton;  //枚举值为非负整数,使用uint
    while (i <= QDialogButtonBox::LastButton) {
        if (i & buttons) {
            createButton(StandardButton(i));
        i = i << 1;
void TipDialog::setStandardButtons(StandardButtons buttons) {
    if (buttons != NoButton)
        createStandardButtons(buttons);
//QString TipDialog::standardTitle(TipDialog::TipIcon icon) {
//    QString title;
//    switch (icon) {
//        case TipDialog::Information:
//            title = "Information";
//            break;
//        case TipDialog::Question:
//            title = "Question";
//            break;
//        case TipDialog::Success:
//            title = "Success";
//            break;
//        case TipDialog::Warning:
//            title = "Warning";
//            break;
//        case TipDialog::Critical:
//            title = "Critical";
//            break;
//        default:
//            break;
//    }
//    if (!title.isEmpty())
//        return title;
//    return QString();
QString TipDialog::getEnumKey(StandardButton button) {
    QMetaEnum metaEnum = QMetaEnum::fromType<StandardButton>();  //获取QMetaEnum对象,为了获取枚举值
    QString str = metaEnum.valueToKey(button);
    if (!str.isEmpty())
        return str;
    return QString();
void TipDialog::addButton(TipDialog::StandardButton button, QDialogButtonBox::ButtonRole buttonRole) {
    QString buttonText = getEnumKey(button);
    QPushButton* pushButton = m_pButtonBox->addButton(buttonText, buttonRole);
    //    if (pushButton->text() == QLatin1String("Yes") && m_text.contains("save", Qt::CaseSensitive)) {
    //        pushButton->setText("Save");
    //    } else if (pushButton->text() == QLatin1String("Yes") && m_text.contains("delete", Qt::CaseSensitive)) {
    //        pushButton->setText("Delete");
    //    }
    //    m_pButtonList.append(pushButton);
    connect(pushButton, &QPushButton::clicked, this, &TipDialog::close);

main.cpp

#include <QApplication>
#include <QMessageBox>
#include "tipdialog.h"
int main(int argc, char* argv[]) {
    QApplication a(argc, argv);
    //TipDialog aa(TipDialog::Question, "Question", "The current project has been modified.\nDo you want to save it?", TipDialog::Yes | TipDialog::No);
    //TipDialog aa(TipDialog::Success, "Success", "Project saved successfully!", TipDialog::Ok);
    //TipDialog aa(TipDialog::Warning, "Warning", "Parsed file not found! Please reconfigure!", TipDialog::Ok);
    TipDialog aa(TipDialog::Critical, "Critical", "Loading failed.Please tryagain!", TipDialog::Ok);
    aa.show();
    return a.exec();

注意:需要在Resources文件中自己手动添加icon图片。

5. v1.0的改进:重新实现弹窗界面(附完整代码)(v2.0)

增加了许多接口,并且之前v1.0版本添加按钮是自己实现的,其实不需要,直接使用QDialogButtonBox的接口会更方便。
MyMessageBox.h

#ifndef MyMessageBox_H
#define MyMessageBox_H
#include <QApplication>
#include <QDebug>
#include <QDialog>
#include <QDialogButtonBox>
#include <QFile>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
#include <QMetaEnum>
#include <QPixmap>
#include <QPushButton>
#include <QVBoxLayout>
class MyMessageBox : public QDialog {
    Q_OBJECT
public:
    enum Icon {
        NoIcon = 0,
        Information = 1,
        Question = 2,
        Success = 3,
        Warning = 4,
        Critical = 5
    Q_ENUM(Icon)  //使用Q_ENUM注册枚举
    enum StandardButton {
        //尽量保持与 QDialogButtonBox::StandardButton 一致,在创建按钮时可能会用到 & 运算
        NoButton = 0x00000000,
        Ok = 0x00000400,
        Save = 0x00000800,
        SaveAll = 0x00001000,
        Open = 0x00002000,
        Yes = 0x00004000,
        YesToAll = 0x00008000,
        No = 0x00010000,
        NoToAll = 0x00020000,
        Abort = 0x00040000,
        Retry = 0x00080000,
        Ignore = 0x00100000,
        Close = 0x00200000,
        Cancel = 0x00400000,
        Discard = 0x00800000,
        Help = 0x01000000,
        Apply = 0x02000000,
        Reset = 0x04000000,
        RestoreDefaults = 0x08000000,
        FirstButton = Ok,
        LastButton = RestoreDefaults
    Q_ENUM(StandardButton)
    Q_DECLARE_FLAGS(StandardButtons, StandardButton)
    Q_FLAG(StandardButtons)
    enum ButtonRole {
        //保持与 QDialogButtonBox::ButtonRole 一致
        InvalidRole = -1,
        AcceptRole,
        RejectRole,
        DestructiveRole,
        ActionRole,
        HelpRole,
        YesRole,
        NoRole,
        ResetRole,
        ApplyRole,
        NRoles
    explicit MyMessageBox(QWidget* parent = nullptr);
    MyMessageBox(Icon icon, const QString& title, const QString& text, StandardButtons buttons,
                 QWidget* parent = nullptr);  //构造函数有默认值的要放后面
    ~MyMessageBox();
    void setTitle(const QString& title);
    Icon icon() const;
    void setIcon(Icon icon);
    QPixmap iconPixmap() const;
    void setIconPixmap(const QPixmap& pixmap);
    QString text() const;
    void setText(const QString& text);
    StandardButtons standardButtons() const;
    void setStandardButtons(StandardButtons buttons);
    StandardButton standardButton(QAbstractButton* button) const;
    QAbstractButton* button(StandardButton which) const;
    ButtonRole buttonRole(QAbstractButton* button) const;
    QAbstractButton* clickedButton() const;
    static StandardButton information(QWidget* parent, const QString& text, QString title = "Message", StandardButtons buttons = Ok);
    static StandardButton question(QWidget* parent, const QString& text, QString title = "Message", StandardButtons buttons = StandardButtons(Yes | No));
    static StandardButton success(QWidget* parent, const QString& text, QString title = "Message", StandardButtons buttons = Ok);
    static StandardButton warning(QWidget* parent, const QString& text, QString title = "Message", StandardButtons buttons = Ok);
    static StandardButton critical(QWidget* parent, const QString& text, QString title = "Message", StandardButtons buttons = Ok);
    static StandardButton showMessageBox(QWidget* parent, Icon icon, const QString& text, QString title, StandardButtons buttons);
    static void setMessageBoxGeometry(QWidget* parent, MyMessageBox& msgBox);
private slots:
    void slotPushButtonClicked(QAbstractButton* button);
private:
    void init();
    void setupLayout();
    QPixmap standardIcon(Icon icon);
    void setClickedButton(QAbstractButton* button);
    void finalize(QAbstractButton* button);
    int dialogCodeForButton(QAbstractButton* button) const;
    void setPushButtonProperty(QList<QAbstractButton*> buttonList);
private:
    QLabel* m_pIconLabel;
    MyMessageBox::Icon m_icon;
    QLabel* m_pTextLabel;
    QLabel* m_pLineLabel;
    QDialogButtonBox* m_pButtonBox;
    QAbstractButton* m_pClickedButton;
//在全局任意地方使用"|"操作符计算自定义的枚举量,需要使用Q_DECLARE_OPERATORS_FOR_FLAGS宏
Q_DECLARE_OPERATORS_FOR_FLAGS(MyMessageBox::StandardButtons)
#endif  // MyMessageBox_H
//在全局任意地方使用"|"操作符计算自定义的枚举量,需要使用Q_DECLARE_OPERATORS_FOR_FLAGS宏
Q_DECLARE_OPERATORS_FOR_FLAGS(MyMessageBox::StandardButtons)
#endif  // MyMessageBox_H

MyMessageBox.cpp

#include "MyMessageBox.h"
#define MESSAGEWIDTH 450  //界面的大小
#define MESSAGEHEIGHT 225
#define TEXTFONTFAMILY "微软雅黑"  //text的字体样式和大小
#define TEXTFONTSIZE 12
#define BUTTONFONTFAMILY "微软雅黑"  //按钮的字体样式和大小
#define BUTTONFONTSIZE 10
#define BUTTONWIDTH 100  //按钮的大小
#define BUTTONHEIGHT 30
MyMessageBox::MyMessageBox(QWidget* parent) :
    QDialog(parent) {
    init();
MyMessageBox::MyMessageBox(Icon icon, const QString& title, const QString& text, StandardButtons buttons, QWidget* parent) :
    QDialog(parent) {
    init();
    setTitle(title);
    setIcon(icon);
    setText(text);
    if (buttons != NoButton)
        setStandardButtons(buttons);
MyMessageBox::~MyMessageBox() {}
void MyMessageBox::setTitle(const QString& title) {
    setWindowTitle(title);
MyMessageBox::Icon MyMessageBox::icon() const {
    return m_icon;
void MyMessageBox::setIcon(MyMessageBox::Icon icon) {
    setIconPixmap(standardIcon(icon));
    m_icon = icon;
QPixmap MyMessageBox::iconPixmap() const {
    return *m_pIconLabel->pixmap();
void MyMessageBox::setIconPixmap(const QPixmap& pixmap) {
    //    m_pIconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    m_pIconLabel->setPixmap(pixmap);
    m_icon = NoIcon;
QString MyMessageBox::text() const {
    return m_pTextLabel->text();
void MyMessageBox::setText(const QString& text) {
    m_pTextLabel->setFont(QFont(TEXTFONTFAMILY, TEXTFONTSIZE));
    m_pTextLabel->setText(text);
MyMessageBox::StandardButtons MyMessageBox::standardButtons() const {
    QDialogButtonBox::StandardButtons standardButtons = m_pButtonBox->standardButtons();
    return MyMessageBox::StandardButtons(int(standardButtons));  //不同类型的枚举转换
void MyMessageBox::setStandardButtons(StandardButtons buttons) {
    QDialogButtonBox::StandardButtons standardButtons = QDialogButtonBox::StandardButtons(int(buttons));
    m_pButtonBox->setStandardButtons(standardButtons);
    //    m_pButtonBox->setStandardButtons(QDialogButtonBox::StandardButtons(int(buttons)));  //上面两句归为一句
    setPushButtonProperty(m_pButtonBox->buttons());
MyMessageBox::StandardButton MyMessageBox::standardButton(QAbstractButton* button) const {
    QDialogButtonBox::StandardButton standardButton = m_pButtonBox->standardButton(button);
    return (MyMessageBox::StandardButton)standardButton;  //转化为当前类的StandardButton类型
QAbstractButton* MyMessageBox::button(MyMessageBox::StandardButton which) const {
    QDialogButtonBox::StandardButton standardButton = QDialogButtonBox::StandardButton(which);
    return m_pButtonBox->button(standardButton);
MyMessageBox::ButtonRole MyMessageBox::buttonRole(QAbstractButton* button) const {
    QDialogButtonBox::ButtonRole buttonRole = m_pButtonBox->buttonRole(button);
    return MyMessageBox::ButtonRole(buttonRole);
QAbstractButton* MyMessageBox::clickedButton() const {
    return m_pClickedButton;
MyMessageBox::StandardButton MyMessageBox::information(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    return showMessageBox(parent, Information, text, title, buttons);
MyMessageBox::StandardButton MyMessageBox::question(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    return showMessageBox(parent, Question, text, title, buttons);
MyMessageBox::StandardButton MyMessageBox::success(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    return showMessageBox(parent, Success, text, title, buttons);
MyMessageBox::StandardButton MyMessageBox::warning(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    return showMessageBox(parent, Warning, text, title, buttons);
MyMessageBox::StandardButton MyMessageBox::critical(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    return showMessageBox(parent, Critical, text, title, buttons);
MyMessageBox::StandardButton MyMessageBox::showMessageBox(QWidget* parent, Icon icon, const QString& text, QString title, StandardButtons buttons) {
    MyMessageBox msgBox(icon, title, text, buttons, parent);
    //静态函数只能调用静态函数,setMessageBoxGeometry()必须声明为静态函数
    setMessageBoxGeometry(parent, msgBox);
    if (msgBox.exec() == -1)
        return MyMessageBox::Cancel;
    return msgBox.standardButton(msgBox.clickedButton());
void MyMessageBox::setMessageBoxGeometry(QWidget* parent, MyMessageBox& msgBox) {
    QRect rect = parent->geometry();
    int x = rect.x() + (rect.width() - msgBox.geometry().width()) / 2;
    int y = rect.y() + (rect.height() - msgBox.geometry().height()) / 2;
    msgBox.setGeometry(x, y, msgBox.geometry().width(), msgBox.geometry().height());
    msgBox.move(x, y);
void MyMessageBox::slotPushButtonClicked(QAbstractButton* button) {
    setClickedButton(button);
    finalize(button);
    close();
void MyMessageBox::init() {
    resize(QSize(MESSAGEWIDTH, MESSAGEHEIGHT));
    setWindowIcon(QIcon(":/new/prefix1/Icon/project.ico"));
    setWindowTitle("Message");
    //对于继承的QDialog,其Flags必须包含Qt::Dialog,不能自定义CustomizeWindowHint
    //否则在构造中指定了parent之后会出现:标题栏消失以及窗口不在正中间
    //setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);  //设置右上角按钮
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowCloseButtonHint;
    setWindowFlags(flags);  //去掉标题栏右上角的问号
    //setAttribute(Qt::WA_DeleteOnClose);                                   //关闭窗口时将窗口释放掉即释放内存
    m_pIconLabel = new QLabel(this);
    m_pIconLabel->setObjectName(QLatin1String("iconLabel"));
    m_pIconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);  //图标不可拉伸和缩小,固定大小
    m_pTextLabel = new QLabel(this);
    m_pTextLabel->setObjectName(QLatin1String("textLabel"));
    m_pTextLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);  //label中的内容可用鼠标选择文本复制,链接激活
    m_pTextLabel->setOpenExternalLinks(true);                           //label中的内容若为链接,可直接点击打开
    m_pLineLabel = new QLabel(this);
    m_pLineLabel->setFrameStyle(QFrame::HLine | QFrame::Sunken);  //Sunken:凹陷,Raised:凸起
    m_pButtonBox = new QDialogButtonBox(this);                    //默认按钮为水平布局Qt::Horizontal
    m_pButtonBox->setObjectName(QLatin1String("buttonBox"));
    connect(m_pButtonBox, &QDialogButtonBox::clicked, this, &MyMessageBox::slotPushButtonClicked);
    setupLayout();
    setModal(true);
    setStyleSheet("QDialog{background-color:rgb(255 , 255 , 255);}"
                  "QPushButton{background-color:#E0E0E0;border: 1px solid #A6A6A6;border-radius:5px;}"
                  "QPushButton:hover{color:white;background-color:#4188FF;border-radius:5px;border: 0px}"
                  //                  "QPushButton{background-color:#E0E0E0;border: 1px solid #C2C2C2;border-radius:5px;}"
                  //                  "QPushButton:hover{background-color:#C2C2C2;border-radius:5px;border: 0px}"
                  "QPushButton:pressed{padding-left:3px;padding-top:3px;}");
void MyMessageBox::setupLayout() {
    QHBoxLayout* HLay = new QHBoxLayout;
    HLay->addWidget(m_pIconLabel, 1, Qt::AlignVCenter | Qt::AlignRight);
    HLay->addWidget(m_pTextLabel, 5, Qt::AlignCenter);
    QHBoxLayout* HLay1 = new QHBoxLayout;
    HLay1->addWidget(m_pButtonBox, Qt::AlignRight);
    //    QMargins margin;
    //    margin.setRight(9);
    //    HLay1->setContentsMargins(margin);  //调节按钮不要太靠右
    QVBoxLayout* VLay = new QVBoxLayout;
    VLay->addLayout(HLay, 10);
    VLay->addWidget(m_pLineLabel, 1);
    VLay->addLayout(HLay1, 4);
    VLay->setSpacing(0);
    setLayout(VLay);
QPixmap MyMessageBox::standardIcon(Icon icon) {
    QPixmap pixmap;
    switch (icon) {
        case MyMessageBox::Information:
            pixmap.load(":/new/prefix1/Image/Information.png");
            break;
        case MyMessageBox::Question:
            pixmap.load(":/new/prefix1/Image/Question.png");
            break;
        case MyMessageBox::Success:
            pixmap.load(":/new/prefix1/Image/Success.png");
            break;
        case MyMessageBox::Warning:
            pixmap.load(":/new/prefix1/Image/Warning.png");
            break;
        case MyMessageBox::Critical:
            pixmap.load(":/new/prefix1/Image/Critical.png");
            break;
        default:
            break;
    if (!pixmap.isNull())
        return pixmap;
    return QPixmap();
void MyMessageBox::setClickedButton(QAbstractButton* button) {
    m_pClickedButton = button;
void MyMessageBox::finalize(QAbstractButton* button) {
    int dialogCode = dialogCodeForButton(button);
    if (dialogCode == QDialog::Accepted) {
        emit accept();
    } else if (dialogCode == QDialog::Rejected) {
        emit reject();
int MyMessageBox::dialogCodeForButton(QAbstractButton* button) const {
    switch (buttonRole(button)) {
        case MyMessageBox::AcceptRole:
        case MyMessageBox::YesRole:
            return QDialog::Accepted;
        case MyMessageBox::RejectRole:
        case MyMessageBox::NoRole:
            return QDialog::Rejected;
        default:
            return -1;
void MyMessageBox::setPushButtonProperty(QList<QAbstractButton*> buttonList) {
    for (int i = 0; i < buttonList.size(); i++) {
        QPushButton* pushButton = qobject_cast<QPushButton*>(buttonList.at(i));
        pushButton->setMinimumSize(BUTTONWIDTH, BUTTONHEIGHT);
        pushButton->setFont(QFont(BUTTONFONTFAMILY, BUTTONFONTSIZE));

注意:需要在Resources文件中自己手动添加icon图片。

QT 自定义提示框 Qt 自定义提示框 类似QMessageBox https://blog.csdn.net/qq_37373742/article/details/127402276?spm=1001.2014.3001.5502 为什么需要设计自定义提示框呢? 1.Qt自带的提示框样式单一; 2.提示框的太小; 3.界面风格跟项目的不搭配 public: MyMessageBox(Icon icon,const QString & title, const QString & text, StandardButtons buttons = NoButton, QWidget * parent):QMessageBox(icon,tit. 简介:Qt5.6版本提供了强大的GUI功能,其中包括标准的MessageBox,但它可能不满足所有个性化界面需求。开发者可以通过继承QDialog或QMessageBox类来设计一个自定义MessageBox,使用Qt的布局管理、控件装饰、信号与槽机制,以及QSS样式表来创建具有特定外观和行为的对话框。此指南涵盖从创建自定义对话框类到测试... QDialog::exec():模态(应用程序级)窗口显示。exec() 先设置modal属性,而后调用 show() 显示对话框,最后启用事件循环。在用户关闭这个对话框之前,不能和同一应用程序中的其它窗口交互。第一行申请的栈空间,函数运行结束后内存释放,弹窗会闪退。但是窗口弹出后可以对其他窗口进行操作,不符合要求。将第四行换用dialog->exec()即可解决。换用第二行申请堆空间可解决。 本文详细的介绍了QMessageBox控件的各种操作,例如:消息提示框的使用、判断消息提示框的按钮、标准图标和自定义图标、定时关闭、自定义样式等操作。information:标准信息提示框。本文作者原创,转载请附上文章出处与本文链接。5. QMessageBox自定义样式。1. 标准信息提示框。2. 判断提示框按钮。3. 提示框自带图标。4. 定时关闭提示框。 在qt quick中,可以使用Popup组件来轻松创建弹出窗口。最后,在弹出窗口内部,我们使用Rectangle和Text组件实现了弹出窗口的基本UI,并添加了一个Button组件,用于关闭弹出窗口。在这个例子中,我们首先创建了一个按钮,当用户点击该按钮时,弹出窗口将显示出来。在这个例子中,我们设置了modal属性为true,这将使弹出窗口成为模态的,阻止用户与其他应用程序部分交互,直到关闭弹出窗口。总之,在qt quick中,使用Popup组件可以很容易地创建自定义的弹出窗口,并实现一些简单的用户交互。