QMessageBox

设置标准按钮:帮助文档代码

1   QMessageBox msgBox;
2   msgBox.setText("The document has been modified.");
3   msgBox.setInformativeText("Do you want to save your changes?");
4   msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
5   msgBox.setDefaultButton(QMessageBox::Save);
6   int ret = msgBox.exec();

显式效果:

The exec() slot returns the StandardButtons value of the button that was clicked.

 1   switch (ret) {
 2     case QMessageBox::Save:
 3         // Save was clicked
 4         break;
 5     case QMessageBox::Discard:
 6         // Don't Save was clicked
 7         break;
 8     case QMessageBox::Cancel:
 9         // Cancel was clicked
10         break;
11     default:
12         // should never be reached
13         break;
14   }

可选标准按钮:

自定义按钮:

选用:

1 QPushButton * addButton(const QString &text, QMessageBox::ButtonRole role)

role的可选值:

 1 void AddStudents::my_add_students_info_ok_slots(){
 2 
 3     //获取lineEdit控件的输入信息
 4     QString name = this->ui->lineedit_name->text();
 5     QString id = this->ui->lineedit_id->text();
 6 
 7     //在QMessageBox中自定义按钮
 8     QMessageBox msgBox;
 9     msgBox.addButton("确定",QMessageBox::AcceptRole);
10     QPushButton * reback_on_cancel = msgBox.addButton("取消",QMessageBox::RejectRole);
11     //设置默认选中是取消按钮
12     msgBox.setDefaultButton(reback_on_cancel);
13     //显式lineEdit控件的输入信息
14     msgBox.setText(name+'
'+id);
15     int ret = msgBox.exec();
16 }

 预定义的四个message boxes:分别显式不同的样式(警告、询问、严重警告、信息)

Static functions are available for creating information(), question(), warning(), and critical() message boxes.

1 [static] QMessageBox::StandardButton QMessageBox::information(QWidget *parent, const QString &title, const QString &text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton = NoButton)

好处,能够快捷的生成一个msg box窗体,样式是预定义样式,显式的内容,包括设置标准按钮或者自定义按钮都在一个函数调用中完成。

 1 void AddStudents::my_add_students_info_ok_slots(){
 2 
 3     //获取lineEdit控件的输入信息
 4     QString name = this->ui->lineedit_name->text();
 5     QString id = this->ui->lineedit_id->text();
 6 
 7     int ret = QMessageBox::information(this,"请确认信息",name+'
'+id,"确认","取消");
 8     if(ret == 0){
 9         //点击第一个按钮-确定按钮
10     }else if(ret == 1){
11         //点击第二个按钮-取消按钮
12     }
13     //...依次类推
14 }

内在的趣味,表面的繁琐
原文地址:https://www.cnblogs.com/data1213/p/10801830.html