欢迎小伙伴的点评✨✨,相互学习、互关必回、全天在线🍳🍳🍳
博主🧑🧑 本着开源的精神交流Qt开发的经验、将持续更新续章,为社区贡献博主自身的开源精神👩🚀
前言
本章节将会给大家带来自定义消息框类的详细使用方法
一、自定义消息框概述
当以上所有消息框都不能满足开发的需求时, Qt 还允许自定义 (Custom) 消息框。对消息框的图标、按钮和内容等都可根据需要进行设定 。
二、效果实例
三、原码解析
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QLabel>
#include <QPushButton>
#include <QGridLayout>
#include <QMessageBox>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = nullptr);
~Dialog();
private:
Ui::Dialog *ui;
QPushButton *CustomBtn;
QLabel *label;
QGridLayout *mainLayout;
private slots:
void showCustomDlg();
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
CustomBtn =new QPushButton;
CustomBtn->setText(tr(" 用户自定义消息对话框实例 ")) ;
label =new QLabel;
label->setFrameStyle(QFrame::Panel|QFrame::Sunken);
mainLayout = new QGridLayout(this);
mainLayout->addWidget(CustomBtn,4,0);
mainLayout->addWidget(label,4,1);
connect(CustomBtn,SIGNAL(clicked()),this,SLOT(showCustomDlg()));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::showCustomDlg()
{
label->setText(tr("Custom Message Box"));
QMessageBox customMsgBox;
customMsgBox.setWindowTitle(tr(" 用户自定义消息框 ")) ; // 设置消息框的标题
QPushButton *yesBtn = customMsgBox.addButton(tr("Yes"),QMessageBox::ActionRole); //(a)
QPushButton *noBtn = customMsgBox.addButton(tr("No"),QMessageBox::ActionRole);
QPushButton *cancelBtn = customMsgBox.addButton(QMessageBox::Cancel); //(b)
customMsgBox.setText(tr(" 这是一个用户自定义消息框! ")); //(c)
customMsgBox.setIconPixmap(QPixmap("./Qt.png")); //(d)
customMsgBox.exec(); //显示此自定义消息框
if (customMsgBox. clickedButton () ==yesBtn)
label->setText("Custom Message Box/Yes");
if(customMsgBox.clickedButton()==noBtn)
label->setText("Custom Message Box/No");
if (customMsgBox. clickedButton () ==cancelBtn)
label->setText("Custom Message Box/Cancel");
return;
}
main.cpp
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
(a)
QPushButton *yesBtn=customMsgBox.addButton(tr(“Yes”),QMessageBox::ActionRole): 定义消息框所需的按钮,由千 QMessageBox: :standardButtons 只提供了常用的一些按钮,并不能满足所有应用的需求,故 QMessageBox 类提供了一个 addButtonO函数来为消息框增加自定义的按钮, addButton() 函数的第 1 个参数为按钮显示的文字,第 2 个参数为按钮类型的描述。
(b)
QPushButton *cancelBtn=customMsgBox.addButton(QMessageBox::Cancel): 为 addButton() 函数加入一个标准按钮。消息框将会按调用 addButton() 函数的先后顺序在消息框中由左至右地依次插入按钮。
(c)
customMsgBox.setText(tr(“这是一个用户自定义消息框!”)):设置自定义消息框中显示的提示信息内容。
(d)
customMsgBox.setlconPixmap(QPixmap(“./Qt.png”)):. 设置自定义消息框的图标。注意此处的照片应放在构建文件夹中
(build-Custom-Desktop_Qt_5_12_2_MinGW_32_bit-Debug)或者新建 Qt Resource File
总结
当所有消息框都不能满足开发的需求时会在应用程序开发中经常用到的