先来看一下最熟悉的QMessageBox::information。我们在以前的代码中这样使用过:
QMessageBox::information(NULL, "Title", "Content", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
现在我们从API中看看它的函数签名:
static StandardButton QMessageBox::information ( QWidget * parent, const QString & title, constQString & text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton );
QMessageBox::critical(NULL, "critical", "Content", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
QMessageBox::warning(NULL, "warning", "Content", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
QMessageBox::question(NULL, "question", "Content", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
QMessageBox::about(NULL, "About", "About this application");
QMessageBox::about(NULL, "About", "About this <font color='red'>application</font>");
运行效果如下:
如果我们想自定义图片的话,也是很简单的。这时候就不能使用这几个static的函数了,而是要我们自己定义一个QMessagebox来使用:
QMessageBox message(QMessageBox::NoIcon, "Title", "Content with icon."); message.setIconPixmap(QPixmap("icon.png")); message.exec();
这里我们使用的是exec()函数,而不是show(),因为这是一个模态对话框,需要有它自己的事件循环,否则的话,我们的对话框会一闪而过哦(感谢laetitia提醒).
需要注意的是,同其他的程序类似,我们在程序中定义的相对路径都是要相对于运行时的.exe文件的地址的。比如我们写"icon.png",意思是是在.exe的当前目录下寻找一个"icon.png"的文件。这个程序的运行效果如下:
QMessageBox::StandardButton rb = QMessageBox::question(NULL, "Show Qt", "Do you want to show Qt dialog?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if(rb == QMessageBox::Yes) { QMessageBox::aboutQt(NULL, "About Qt"); }
如果要使用构造函数的方式,那么我们就要自己运行判断一下啦:
QMessageBox message(QMessageBox::NoIcon, "Show Qt", "Do you want to show Qt dialog?", QMessageBox::Yes | QMessageBox::No, NULL); if(message.exec() == QMessageBox::Yes) { QMessageBox::aboutQt(NULL, "About Qt"); }

