PyQt5使用代码让窗口居中

1.获取屏幕的坐标系
2.获取窗口的坐标系
3.移动窗口,使其坐标为width = (屏幕坐标系.width - 窗口坐标系.width)/ 2 。使其height = (屏幕坐标系.height - 窗口坐标系.height)/2

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


# 定义一个类,继承主窗口“QMainWindow”
class CenterForm(QMainWindow):
    # 在构造函数init中初始化
    def __init__(self):
        # 调用父类
        super(CenterForm, self).__init__()
        # 设置主窗口标题
        self.setWindowTitle('让窗口居中')
        # 设置窗口尺寸
        self.resize(400, 300)

    def center(self):
        # 获取屏幕坐标系
        screen = QDesktopWidget().screenGeometry()
        # 获取窗口坐标系
        progrem_size = self.geometry()
        newLeft = (screen.width() - progrem_size.width()) / 2
        newtop = (screen.height() - progrem_size.height()) / 2
        self.move(newLeft, newtop)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = CenterForm()
    main.show()
    sys.exit(app.exec_())

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容