【QT】如何自定义QMessageBox的窗口大小,通过继承QDialog重新实现美观的弹窗

news2024/10/6 16:16:06

目录

  • 1. QMessageBox原有的弹窗
  • 2. 网上第一种方法:通过样式表setStyleSheet实现改变弹窗大小(总体不美观)
  • 3. 网上第二种方法:重写ShowEvent()改变弹窗大小(总体也不美观)
  • 4. 最好的办法:继承QDialog重新实现弹窗界面(附完整代码)(v1.0)
  • 5. v1.0的改进:重新实现弹窗界面(附完整代码)(v2.0)

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 <QDebug>
#include <QDialog>
#include <QDialogButtonBox>
#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);

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;

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

MyMessageBox.cpp

#include "MyMessageBox.h"

#define fontFamily "微软雅黑"
#define fontSize 12

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);
    //    setupLayout();
}

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(fontFamily, fontSize));
    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)));  //上面两句归为一句
}

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) {
    MyMessageBox msgBox(Information, title, text, buttons, parent);
    if (msgBox.exec() == -1)
        return MyMessageBox::Cancel;
    return msgBox.standardButton(msgBox.clickedButton());
}

MyMessageBox::StandardButton MyMessageBox::question(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    MyMessageBox msgBox(Question, title, text, buttons, parent);
    if (msgBox.exec() == -1)
        return MyMessageBox::Cancel;
    return msgBox.standardButton(msgBox.clickedButton());
}

MyMessageBox::StandardButton MyMessageBox::success(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    MyMessageBox msgBox(Success, title, text, buttons, parent);
    if (msgBox.exec() == -1)
        return MyMessageBox::Cancel;
    return msgBox.standardButton(msgBox.clickedButton());
}

MyMessageBox::StandardButton MyMessageBox::warning(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    MyMessageBox msgBox(Warning, title, text, buttons, parent);
    if (msgBox.exec() == -1)
        return MyMessageBox::Cancel;
    return msgBox.standardButton(msgBox.clickedButton());
}

MyMessageBox::StandardButton MyMessageBox::critical(QWidget* parent, const QString& text, QString title, StandardButtons buttons) {
    MyMessageBox msgBox(Critical, title, text, buttons, parent);
    if (msgBox.exec() == -1)
        return MyMessageBox::Cancel;
    return msgBox.standardButton(msgBox.clickedButton());
}

void MyMessageBox::slotPushButtonClicked(QAbstractButton* button) {
    setClickedButton(button);
    finalize(button);
    close();
}

void MyMessageBox::init() {
    resize(QSize(450, 225));
    setWindowIcon(QIcon(":/new/prefix1/Icon/project.ico"));
    setWindowTitle("Message");
    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_pLineLabel = new QLabel(this);
    m_pLineLabel->setFrameStyle(QFrame::HLine | QFrame::Sunken);  //Sunken:凹陷,Raised:凸起
    m_pButtonBox = new QDialogButtonBox(this);
    m_pButtonBox->setObjectName(QLatin1String("buttonBox"));
    connect(m_pButtonBox, &QDialogButtonBox::clicked, this, &MyMessageBox::slotPushButtonClicked);

    setupLayout();
}

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 accepted();
    } else if (dialogCode == QDialog::Rejected) {
        emit rejected();
    }
}

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;
    }
}

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/706189.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

centos安装k8s

1. 前置 俩台centos服务器,不过多说明,教程基于centos 2. hosts配置 我这样配置&#xff0c;最后没发现那块有联动&#xff0c;望大佬更正 vim /etc/hosts 在末尾添加 192.***** master 192.*** note3. 防火墙 说是要关闭防火墙&#xff0c;我俩台服务器都是基于内网&…

服务器数据库中遭受Devos勒索病毒攻击后解密处理方法,勒索病毒数据恢复

在当今数字化时代&#xff0c;服务器数据库的安全性备受关注。然而&#xff0c;网络安全威胁依然存在&#xff0c;勒索病毒如Devos仍然是一种常见的攻击计算机病毒。最近&#xff0c;收到很多企业的求助&#xff0c;企业的财务系统账套遭到了Devos勒索病毒攻击&#xff0c;导致…

js数组中对象的替换,替换原数组 lodash中一些常用的方法(很实用)

代码 let myArray [{name: John, age: 25},{name: Alice, age: 30},{name: Bob, age: 35} ];// 要替换的对象 let objToReplace {name: Alice, age: 30};// 替换为的对象 let replacementObj {name: Alex, age: 28};// 使用forEach方法 myArray.forEach((obj, index) > …

浙大滨江院Om中心发布首个大规模图文配对遥感数据集,让通用基础模型也能服务遥感领域...

写在前面 2021 年年底&#xff0c;OpenAI 发布了 CLIP&#xff0c;利用带噪的图像-文本配对数据预训练的视觉语言模型&#xff0c;展示了前所未有的图像-文本关联能力&#xff0c;在各种下游任务中取得了惊人的结果。虽然取得了很大的进展&#xff0c;但是这类通用视觉语言基础…

Visual C++中的虚函数和纯虚函数(以策略设计模式为例)

我是荔园微风&#xff0c;作为一名在IT界整整25年的老兵&#xff0c;今天来说说Visual C中的虚函数和纯虚函数。该系列帖子全部使用我本人自创的对比学习法。也就是当C学不下去的时候&#xff0c;就用JAVA实现同样的代码&#xff0c;然后再用对比的方法把C学会。 直接说虚函数…

微信小程序 rich-text富文本框 怎么设置里面节点的样式

1、在JS中我们获取数据&#xff0c;在没有类名的情况下 使用正则匹配你想要添加演示的节点 res[1].data[0].f_content为rich-text里面的节点 如图 代码&#xff1a;让获取的节点中的图片的最大宽度为100%,高度为auto this.content res[1].data[0].f_content.replace(/\<…

数据库连接与操作怎么学习? - 易智编译EaseEditing

学习数据库连接和操作是进行数据管理和处理的关键技能之一。下面是一些建议&#xff0c;可以帮助您学习数据库连接和操作&#xff1a; 学习数据库基础知识&#xff1a; 首先&#xff0c;了解数据库的基本概念、术语和原理。掌握关系型数据库和非关系型数据库的特点以及它们之…

Spring Boot中的Elasticsearch自动配置

Spring Boot中的Elasticsearch自动配置 Elasticsearch是一个基于Lucene的分布式全文搜索引擎&#xff0c;它在搜索、分析等方面具有出色的表现。Spring Boot中的Elasticsearch自动配置为我们提供了一种快速集成Elasticsearch的方式&#xff0c;使我们可以在Spring Boot应用程序…

【Unity每日一记】常见的类你都掌握了吗,没有就过来看看吧

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;uni…

layui弹出层laydate时间选择一闪而过,无法弹出时间选择

问题&#xff1a;layUI日期框弹不出&#xff0c;一闪而过 laydate.render({elem: #ctime,type: datetime,trigger:click }); 解决方案&#xff1a;关键代码&#xff0c;添加如下代码 trigger:click 实现效果

浏览器基础原理-安全: HTTPS

HTTP协议的历史: HTTP协议的目的很单纯, 就是为了传输超文本文件, 所以早期的 HTTP 一直保持着明文传输数据的特征, 但是中间很有可能会被截取或者篡改, 即收到中间人攻击. 解析HTTP协议栈层面: HTTPS往里面加入了安全层, 它的指责是: 对发起HTTP请求的数据进行加密和对接收…

Redis实战篇(二)

三、优惠卷秒杀 3.1 全局唯一ID 每个店铺都可以发布优惠券&#xff1a; 当用户抢购时&#xff0c;就会生成订单并保存到tb_voucher_order这张表中&#xff0c;而订单表如果使用数据库自增ID就存在一些问题&#xff1a; id的规律性太明显 受单表数据量的限制 场景分析一&am…

初学mybatis(二)CRUD操作及配置解析

学习回顾&#xff1a;初学mybatis&#xff08;一&#xff09; 一、namespace 1、将上面案例中的UserMapper接口改名为 UserDao&#xff1b;2、将UserMapper.xml中的namespace改为为UserDao的路径 .3、再次测试 结论&#xff1a; 配置文件中namespace中的名称为对应Mapper接口或…

Python基本操作

前言 啦啦啦&#xff0c;现在开始,打算做一期Python基础教程&#xff0c;欢迎大家来看哦&#xff01; 导读 这期文章真的是Python基础中的基础&#xff0c;相信有一定编程基础的小伙伴们都一定能看懂的… 本文共分为以下几个部分&#xff1a; 数与运算符基本输入输出注释模…

Linux环境安装openJDK

现在越来越多的开发者使用 openJDK &#xff0c;当然这也是一种趋势 官网下载&#xff1a; https://jdk.java.net/java-se-ri/8-MR5这里以 jdk8 为例 配置环境变量 看网上的教程&#xff0c;好多人都推荐去这个官网下载&#xff1a; https://hg.openjdk.org/其实这个是 O…

算法笔记——数组篇

整理一下刷过的题型&#xff0c;持续更新&#xff0c;参照代码随想录 代码随想录数组篇 二分法 力扣相关题目&#xff1a; 704. 二分查找 只适用于排序有序数组&#xff0c;且没有重复元素。主要是有两种写法&#xff0c;二分查找涉及的很多的边界条件&#xff0c;逻辑比较简单…

V-Box智能车载终端-OBUYZN2

1 产品概览 OBUYZN2型智能车载终端&#xff08;以下简称&#xff09;是 型智能车载终端&#xff08;以下简称&#xff09;是 型智能车载终端&#xff08;以下简称&#xff09;是 型智能车载终端&#xff08;以下简称&#xff09;是 组成智能网联 系统 的核心数据交互设备 &…

Java 顶层类(top-level class)的访问控制修饰符

在Java中&#xff0c;处于最外层的类就是顶层类&#xff08;top-level class&#xff09;&#xff0c;类的声明外面再没有其它的类包裹。 顶层类的访问控制修饰符只能是public、或者包访问控制修饰符&#xff08;也就是无访问控制修饰符&#xff09;。 访问控制修饰符访问范围…

用codetyphon开发一个单机版跨平台数据处理小软件

目录 1 前言 2 一种可能的方案 2.1 数据存储使用dbf格式 2.2 用Lazarus或CT开发 2.3 根据外部csv或者excel电子表格快速建表 2.4 用python汇总和审核 3 当前进度 3.1 根据excel电子表格快速自动建表和导入数据 3.2 显示数据 3.3 建立测试数据库 1 前言 现在各种现成的…

Vue天气案例

绑定事件的时候&#xff1a;xxx"yyy" yyy可以写一些简单的语句。 <body><div id"root"><h2>今天天气很{{info}}</h2><button click"changeWether">切换天气</button></div> </body><scr…