活动屏幕上的 PyQt4 中心窗口

新手上路,请多包涵

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

 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 处打开。我需要在活动屏幕上打开窗口并将此窗口移动到此屏幕的中央。谢谢!

原文由 Applejohn 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 518
2 个回答

修改你的 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 和该屏幕的中心点。使用这种方法,即使显示器分辨率不同,您也应该能够将窗口放置在屏幕中央。

原文由 Andy 发布,翻译遵循 CC BY-SA 3.0 许可协议

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())

原文由 NL23codes 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题