Python学习笔记之PyQt5窗口居中对齐 - helloWorld

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xsophiax/article/details/99436000

在工作中有时候要某些窗口居中,就要使用到如下code逻辑。

import sys
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication


class helloWorld(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.resize(250, 150)
        self.center()

        self.setWindowTitle('helloWorld - center')
        self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = helloWorld()
    sys.exit(app.exec_())
QtGui.QDesktopWidget提供了用户的桌面信息,包括屏幕的大小。
self.center()
这个方法是调用我们下面写的,实现对话框居中的方法。
qr = self.frameGeometry()
获得主窗口所在的框架。
cp = QDesktopWidget().availableGeometry().center()
获取显示器的分辨率,然后得到屏幕中间点的位置。
qr.moveCenter(cp)
然后把主窗口框架的中心点放置到屏幕的中心位置。
self.move(qr.topLeft())
然后通过move函数把主窗口的左上角移动到其框架的左上角,这样就把窗口居中了。

程序预览:

猜你喜欢

转载自blog.csdn.net/xsophiax/article/details/99436000
今日推荐