PyQt4活动屏幕上的中心窗口

问题描述 投票:13回答:2

我如何在活动屏幕上居中窗口而不是在普通屏幕上?此代码将窗口移动到一般屏幕的中心,而不是活动屏幕:

import sys
from PyQt4 import QtGui

class MainWindow(QtGui.QWidget):

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

        self.initUI()

    def initUI(self):

        self.resize(640, 480)
        self.setWindowTitle('Backlight management')
        self.center()

        self.show()

    def center(self):
        frameGm = self.frameGeometry()
        centerPoint = QtGui.QDesktopWidget().availableGeometry().center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())

def main():
    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

如果我从initUI()中删除self.center(),则在活动屏幕上的0x0上打开窗口。我需要在活动屏幕上打开窗口并将此窗口移动到此屏幕的中心。 Thansk!

python user-interface python-3.x pyqt pyqt4
2个回答
24
投票

修改您的center方法如下:

def center(self):
    frameGm = self.frameGeometry()
    screen = QtGui.QApplication.desktop().screenNumber(QtGui.QApplication.desktop().cursor().pos())
    centerPoint = QtGui.QApplication.desktop().screenGeometry(screen).center()
    frameGm.moveCenter(centerPoint)
    self.move(frameGm.topLeft())

此功能基于鼠标点所在的位置。它使用screenNumber函数来确定鼠标当前处于活动状态的屏幕。然后它找到该监视器的screenGeometry和该屏幕的中心点。使用此方法,即使显示器分辨率不同,您也应该能够将窗口置于屏幕中央。


1
投票

PyQt5用户的一个更正:

import PyQt5

def center(self):
    frameGm = self.frameGeometry()
    screen = PyQt5.QtWidgets.QApplication.desktop().screenNumber(PyQt5.QtWidgets.QApplication.desktop().cursor().pos())
    centerPoint = PyQt5.QtWidgets.QApplication.desktop().screenGeometry(screen).center()
    frameGm.moveCenter(centerPoint)
    self.move(frameGm.topLeft())
© www.soinside.com 2019 - 2024. All rights reserved.