Qt中与用户做信息交互的消息框用起来非常简单方便,如:消息、警告、错误、关于、提问、用户自定义等等!这些对话框都是QMessageBox类提供的,除用户自定义的对话框外其它的对话框均可以直接引用,它们都是类提供的静态函数。这些静态函数前几个形参分别为:父对象指针、标题、提示信息,其余的形参用户可以根据不同类型的对话框,根据需要定制,并制定默认被选中的按钮,按钮的类型通过QMessageBox类提供的枚举值来确定如:QMessageBox::Ok(显示“Ok”按钮),当用户选择对应的按钮时,函数会返回用户选择的该枚举值,供程序区别处理。
闲话少说,上程序!
一、基于QMessageBox的静态函数对话框
void Dialog::qtAbout()
{
QMessageBox::about(this,"About",tr("This is about message box!"));
}
void Dialog::qtAboutQt()
{
QMessageBox::aboutQt(this,"About Qt");
}
void Dialog::qtQuestion()
{
switch(QMessageBox::question(this,"Question",
tr("This is a question dialog, Please choose your select!"),
QMessageBox::Ok|QMessageBox::Cancel,QMessageBox::Cancel))
{
case QMessageBox::Ok:
this->setWindowTitle("Ok Selected!");
break;
case QMessageBox::Cancel:
this->setWindowTitle("Cancel Selected!");
break;
default:
break;
}
}
void Dialog::qtInformation()
{
QMessageBox::information(this,"Information dialog",tr("Timeout,You can try again later!"));
}
void Dialog::qtCritical()
{
QMessageBox::critical(this,"Critical",tr("Critial error!"));
}
void Dialog::qtWarning()
{
switch(QMessageBox::warning(this,"Warning dialog",tr("Do you want to save changes?"),
QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel,QMessageBox::Save))
{
case QMessageBox::Save:
this->setWindowTitle("Save selected!");
break;
case QMessageBox::Discard:
this->setWindowTitle("Discard selected!");
break;
case QMessageBox::Cancel:
this->setWindowTitle("Cancel selected!");
break;
default:
break;
}
}
在QDialog的派生类中定义了槽来测试对话框,同时又实例化了相应的按钮对象,将按钮对象的Clicked()信号与这些槽连接起来,实现了相应功能展示。
二、基于QMessageBox的用户自定义对话框
void Dialog::qtCustom(){
QMessageBox customMessage;//实例化QMessageBox对象customMessage.setWindowTitle("Custom message box!");//设置对话框标题QPushButton *testButton = customMessage.addButton(tr("Test"),QMessageBox::ActionRole);//插入按钮QPushButton *closeButton = customMessage.addButton(tr("Close"),QMessageBox::ActionRole);//插入按钮QPushButton *cancelButton = customMessage.addButton(QMessageBox::Cancel);//插入按钮customMessage.setIconPixmap(QPixmap("./images/qtcreator.png"));//为对话框设置图片customMessage.setText("This is a custom message box!");//为对话框设置信息提示customMessage.exec();//进入对话框消息循环显示对话框,等待用户选择if (customMessage.clickedButton()== testButton)//判断用户操作{this->setWindowTitle("Test Button was Clicked!");}else if (customMessage.clickedButton()== closeButton)//判断用户操作{this->setWindowTitle("Close Button was Clicked!");}else if (customMessage.clickedButton()== cancelButton)//判断用户操作{this->setWindowTitle("Cancel Button was Clicked!");}}
两种对话框的使用方法介绍结束了,仔细的总结一下,结论就是:怎么会这么简单、好用呢???