PyQt5是基于Python语言的Qt GUI框架。QMessageBox是PyQt5中的一个弹窗控件,可以用于提示用户信息或者确认操作。
QMessageBox的完整使用攻略如下:
导入模块
from PyQt5.QtWidgets import QMessageBox, QApplication
import sys
创建QMessageBox
确认对话框
# 创建确认对话框
reply = QMessageBox.question(
self, 'Message', "Are you sure to exit?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
# 处理用户的回复
if reply == QMessageBox.Yes:
QApplication.quit()
提示对话框
# 创建提示对话框
QMessageBox.information(self, 'Title', 'Content')
显示QMessageBox
self.show()
示例一:代码说明
下面是一个PyQt5的示例,演示如何创建一个确认对话框,提示用户是否退出应用程序。
from PyQt5.QtWidgets import QMessageBox, QApplication, QWidget, QPushButton
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Message box')
qbtn = QPushButton('Quit', self)
qbtn.clicked.connect(self.showDialog)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
def showDialog(self):
# 创建确认对话框
reply = QMessageBox.question(
self, 'Message', "Are you sure to exit?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
# 处理用户的回复
if reply == QMessageBox.Yes:
QApplication.quit()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
示例二:代码说明
下面是一个PyQt5的示例,演示如何创建一个提示对话框,提示用户输入用户名和密码。
from PyQt5.QtWidgets import QMessageBox, QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Message box')
self.name_label = QLabel('Name:', self)
self.name_input = QLineEdit(self)
self.password_label = QLabel('Password:', self)
self.password_input = QLineEdit(self)
self.password_input.setEchoMode(QLineEdit.Password)
vbox = QVBoxLayout()
vbox.addWidget(self.name_label)
vbox.addWidget(self.name_input)
vbox.addWidget(self.password_label)
vbox.addWidget(self.password_input)
qbtn = QPushButton('Login', self)
qbtn.clicked.connect(self.showDialog)
vbox.addWidget(qbtn)
self.setLayout(vbox)
def showDialog(self):
# 获取用户名和密码
name = self.name_input.text()
password = self.password_input.text()
# 判断输入是否为空
if not name or not password:
QMessageBox.critical(self, 'Error', 'Name or password cannot be empty')
else:
# 显示提示对话框
QMessageBox.information(self, 'Title', 'Login success')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
以上是关于PyQt5 - QMessageBox的完整使用攻略,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:PyQt5 – QMessageBox - Python技术站