PyQt5 - QMessageBox



QMessageBox 是一個常用的模態對話方塊,用於顯示一些資訊訊息,並可以選擇性地要求使用者透過點選其上的任何一個標準按鈕來響應。每個標準按鈕都有一個預定義的標題、一個角色和一個預定義的十六進位制數字。

與 QMessageBox 類相關的重要的方法和列舉在下面的表格中給出:

序號 方法及說明
1

setIcon()

顯示與訊息嚴重性相對應的預定義圖示

  • 提問
  • 資訊
  • 警告
  • 嚴重錯誤
2

setText()

設定要顯示的主訊息文字

3

setInformativeText()

顯示附加資訊

4

setDetailText()

對話方塊顯示“詳細資訊”按鈕。點選此按鈕後顯示此文字。

5

setTitle()

顯示對話方塊的自定義標題

6

setStandardButtons()

要顯示的標準按鈕列表。每個按鈕都與以下內容相關聯:

QMessageBox.Ok 0x00000400

QMessageBox.Open 0x00002000

QMessageBox.Save 0x00000800

QMessageBox.Cancel 0x00400000

QMessageBox.Close 0x00200000

QMessageBox.Yes 0x00004000

QMessageBox.No 0x00010000

QMessageBox.Abort 0x00040000

QMessageBox.Retry 0x00080000

QMessageBox.Ignore 0x00100000

7

setDefaultButton()

將按鈕設定為預設按鈕。如果按下 Enter 鍵,則會發出 clicked 訊號。

8

setEscapeButton()

將按鈕設定為按下 Escape 鍵時被視為已點選。

示例

在下面的示例中,頂級視窗上按鈕的點選訊號與連線的函式相連,該函式顯示訊息框對話方塊。

msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")

setStandardButton() 函式顯示所需的按鈕。

msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

buttonClicked() 訊號連線到一個槽函式,該函式識別訊號源的標題。

msg.buttonClicked.connect(msgbtn)

示例的完整程式碼如下:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QPushButton(w)
   b.setText("Show message!")
   
   b.move(100,50)
   b.clicked.connect(showdialog)
   w.setWindowTitle("PyQt MessageBox demo")
   w.show()
   sys.exit(app.exec_())

def showdialog():
   msg = QMessageBox()
   msg.setIcon(QMessageBox.Information)
   
   msg.setText("This is a message box")
   msg.setInformativeText("This is additional information")
   msg.setWindowTitle("MessageBox demo")
   msg.setDetailedText("The details are as follows:")
   msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
   msg.buttonClicked.connect(msgbtn)

   retval = msg.exec_()

def msgbtn(i):
   print ("Button pressed is:",i.text())

if __name__ == '__main__':
   window()

以上程式碼產生以下輸出。單擊主視窗的按鈕時,將彈出訊息框。

QMessageBox Output

如果單擊訊息框上的“確定”或“取消”按鈕,則會在控制檯上產生以下輸出:

Button pressed is: OK
Button pressed is: Cancel
廣告