# -*- coding: utf-8 -*-
"""
Created on Sat May 9 14:46:56 2020
@author: Giyn
"""
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
class Simple_Window(QWidget):
def __init__(self):
super(Simple_Window, self).__init__() # 使用super函數可以實現子類使用父類的方法
self.button = QPushButton("Question", self)
self.button.clicked.connect(self.show_msg_box)
def show_msg_box(self, button):
msg_box = QMessageBox(self) # 實例化一個QMessageBox對象
msg_box.setWindowTitle("Question") # 設置對話框的標題
msg_box.setText("Do you want to save it?") # 設置對話框的內容
msg_box.setIcon(QMessageBox.Question)
# 調用addButton方法傳入字符串,確定按鈕扮演的角色
msg_box.addButton("是", QMessageBox.YesRole)
msg_box.addButton("否", QMessageBox.NoRole)
msg_box.exec()
if msg_box.clickedButton().text() == "是": # clickedButton方法返回用戶按下的按鈕
self.close()
print("保存成功!")
else:
self.close()
print("退出程序!")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Simple_Window()
window.show()
sys.exit(app.exec())
Output:
After clicking “是”:
After clicking “否”:
QMessageBox對話框的圖標參數:
QMessageBox.NoIcon
QMessageBox.Question
QMessageBox.Information
QMessageBox.Warning
QMessageBox.Critical
QMessageBox中常見的按鈕角色:
QMessageBox::AcceptRole
QMessageBox::RejectRole
QMessageBox::YesRole
QMessageBox::NoRole
clickedButton
方法返回用戶按下的按鈕
Reference:https://study.163.com/course/courseLearn.htm?courseId=1208995818