002_PyQt5 - 让主窗口居中显示

主窗口居中展示

PyQt5无封装好的让屏幕居中的方法,需要自己计算并将屏幕移动至居中位置:

以下center()函数为设置居中的函数
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QDesktopWidget

class CenterFrom(QMainWindow):
    def __init__(self, parent=None):
        super(CenterFrom, self).__init__(parent)

        # 设置主窗口标题
        self.setWindowTitle('第一个界面')

        # 设置窗口尺寸
        self.resize(400, 300)

    def center(self):
        # 得到屏幕座标
        screen = QDesktopWidget().screenGeometry()
        # 获取窗口座标
        size = self.geometry()
        # 计算居中位置
        newleft = (screen.width() - size.width())/2
        newTop = (screen.height() - size.height())/2
        # 移动到居中位置
        self.move(newleft, newTop)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = CenterFrom()
    main.show()

    sys.exit(app.exec_())
    
运行结果如下:在这里插入图片描述
发布了7 篇原创文章 · 获赞 15 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章