QMessageBox::information(NULL, "Title", "Content", |
這是比較經常使用的一種用法,效果以下:c++
information原型:函數
StandardButton QMessageBox::information(QWidget * parent, const QString & title, const QString & text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton) [static] |
示例1:this
QMessageBox::information(NULL, "Title", "Content"); |
此時第四第五爲默認參數,效果:spa
示例2:指針
QMessageBox::information(NULL, "Title", "Content",QMessageBox::Yes|QMessageBox::No); |
此時效果(與圖1相同):code
示例三:orm
QMessageBox::information(NULL, "Title", "Content",QMessageBox::Yes|QMessageBox::No| |
添加多個按鈕用|運算符鏈接,效果:對象
按鈕類型參考:blog
enum StandardButton { |
會建立消息提示框後,咱們怎麼知道用戶點了什麼呢,看以下小例子:繼承
QMessageBox:: StandardButton result= QMessageBox::information(NULL, "Title", "Content",QMessageBox::Yes|QMessageBox::No); |
critical adj. 關鍵的; 批評的,愛挑剔的; 嚴重的; 極重要的;
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); |
效果:
原型:static void about(QWidget *parent, const QString &title, const QString &text);
QMessageBox::about(NULL, "About", "by hjwblog.com"); |
效果:
若是是本身建立的QMessageBox對象,而不是用上面的static函數
示例1:
void MainWindow::on_pushButton_clicked() |
這裏在按鈕的clicked槽裏面建立了一個QMessageBox,可是這樣會出現消息框一閃而過。這是由於c++局部變量的生命週期結束了,QMessageBox messageBox
是函數局部變量,函數結束後它的生命週期也結束了。
示例2:
void MainWindow::on_pushButton_clicked() |
效果:
這樣就好理解了,c++函數裏面的static變量在函數結束時不會被回收。
示例3:
void MainWindow::on_pushButton_clicked() |
這樣寫也能顯示提示框,可是這樣會內存泄漏。
示例4:
前面的用法都不太完美,咱們但願能方便的顯示提示框而且獲取用戶點擊了哪一個按鈕。由於QMessageBox
繼承QDialog
,而QDialog
有一個神奇的函數exec()
,調用這個函數後,消息循環會在這個函數裏面進行更新,而調用它的函數是被「暫停」的,就是說等用戶點擊按鈕後,調用exec()
的函數才繼續執行。
直接上代碼:
void MainWindow::on_pushButton_clicked() |
上面的代碼實現了點擊按鈕退出,而且在退出前肯定的功能。exec()
的返回值和前面的information()
同樣,是整數(information()是枚舉)。能夠經過返回值來肯定用戶點擊了哪一個按鈕。
QMessageBox對象調用exec()
函數能實現與前面的幾個靜態函數類似的功能。