本文共 2390 字,大约阅读时间需要 7 分钟。
PyQt5 Message Box与窗口居中示例
在PyQt5中,消息框和窗口居中的实现是日常开发中的常见需求。以下将详细介绍如何在PyQt5中创建消息框以及如何将窗口居中。
首先,让我们看看如何在PyQt5中创建一个带有确认按钮的消息框。以下是一个简单的PyQt5脚本:
#!/usr/bin/python"""ZetCode PyQt5 tutorialThis program shows a confirmation message box when we click on the close button of the application window.Author: Jan BodnarWebsite: zetcode.com"""import sysfrom PyQt5.QtWidgets import QWidget, QMessageBox, QApplicationclass Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Message box') self.show() def closeEvent(self, event): reply = QMessageBox.question( self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No ) if reply == QMessageBox.Yes: event.accept() else: event.ignore()def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())if __name__ == '__main__': main() 定义消息框:使用QMessageBox.question()方法创建一个带有确认按钮的消息框。该方法返回一个QMessageBox.Result类型的值,表示用户选择的按钮。
设置参数:第一个参数是父窗口,第二个是标题,第三个是显示在消息框中的文本。第四个参数是按钮组合,第五个参数是默认按钮。
处理返回值:根据返回值判断用户是否点击了"是"或"否"按钮,并相应地处理事件。
为了确保窗口在屏幕上居中,我们可以使用QDesktopWidget和几何功能。以下是一个实现窗口居中的PyQt5脚本:
#!/usr/bin/python"""ZetCode PyQt5 tutorialThis program centers a window on the screen.Author: Jan BodnarWebsite: zetcode.com"""import sysfrom PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplicationclass Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.resize(250, 150) self.center() self.setWindowTitle('Center') self.show() def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())if __name__ == '__main__': main() 获取窗口几何:qr = self.frameGeometry()获取当前窗口的几何形状。
计算屏幕中心:cp = QDesktopWidget().availableGeometry().center()计算屏幕的可用区域中心点。
移动窗口中心:qr.moveCenter(cp)将窗口的几何形状移动到屏幕中心。
调整窗口位置:self.move(qr.topLeft())将窗口的左上角移动到几何形状的左上角,从而实现居中。
通过以上代码,我们可以轻松地在PyQt5中创建消息框并将窗口居中。这些建议在实际开发中非常实用,可以提升用户体验。
转载地址:http://mcxfk.baihongyu.com/