這次來說一下QMessageBox以及類似的幾種對話框。其實,我們已經用過QMessageBox了,就在之前的幾個程序中。不過,當時是大略的說了一下,現在專門來說說這幾種對話框。先來看一下最熟悉的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”);
}
其實道理上也是差不多的。