QMessageBox
QMessageBox類提供了一個模式對話框,用於通知用戶或詢問用戶問題並接收答案。
在圖形用戶界面中,對話框(又稱對話方塊)是一種特殊的視窗,用來在用戶界面中向用戶顯示信息,或者在需要的時候獲得用戶的輸入響應。之所以稱之爲“對話框”是因爲它們使計算機和用戶之間構成了一個對話——或者是通知用戶一些信息,或者是請求用戶的輸入,或者兩者皆有。—— 維基百科
對話框可以增加程序與用戶的交互能力,有時可以避免一些失誤,如文件忘記保存:
QMessageBox提供了多種對話框:
以詢問框爲例:
QMessage.question(parent, title, content, button)
- parent:表示對話框所歸屬的程序窗口。填寫父類(通常爲self);若不屬於任何程序窗口,爲None。
- title:標題。
- content:內容。
- button:對話框按鈕。
QMessage.question(None, ‘Question’, ‘Do you want to save it?’, QMessageBox.Yes | QMessageBox.No)
QMessage.question 的返回值是 QMessageBox.Yes
或 QMessageBox.No
。
多個對話框按鈕用 連接
除此以外,QMessageBox還提供了以下按鈕:
QMessageBox.Ok
QMessageBox.Close
QMessageBox.Cancel
QMessage.Open
QMessage.Save
# -*- coding: utf-8 -*-
"""
Created on Sat May 9 14:05:57 2020
@author: Giyn
"""
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QMessageBox
class Simple_Window(QWidget):
def __init__(self):
super(Simple_Window, self).__init__() # 使用super函數可以實現子類使用父類的方法
self.setWindowTitle("QMessageBox")
self.resize(400, 200)
self.button1 = QPushButton("Question", self) # self是指定的父類Simple_Window,表示QLabel屬於Simple_Window窗口
self.button2 = QPushButton("Information", self)
# 連接信號和槽
self.button1.clicked.connect(lambda: self.show_msg_box(self.button1)) # 槽函數帶有參數,使用lambda表達式封裝函數
self.button2.clicked.connect(lambda: self.show_msg_box(self.button2))
self.v_layout = QVBoxLayout() # 實例化一個QVBoxLayout對象
self.v_layout.addWidget(self.button1)
self.v_layout.addWidget(self.button2)
self.setLayout(self.v_layout) # 調用窗口的setLayout方法將總佈局設置爲窗口的整體佈局
def show_msg_box(self, button):
if button == self.button1:
QMessageBox.question(self, "Question", "Do you want to save it?", QMessageBox.Yes | QMessageBox.No)
elif button == self.button2:
QMessageBox.information(self, "Information", "I am an information.", QMessageBox.Ok)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Simple_Window()
window.show()
sys.exit(app.exec())
Output:
After clicking “Question”:
After clicking “Information”:
Reference:https://study.163.com/course/courseLearn.htm?courseId=1208995818