我希望我的项目主窗口能够显示在屏幕中央。当我调用“self.show()”时,窗口会显示在屏幕中央。
class ExampleWindow (QtGui.QMainWindow):
def __init__ (self, parent=None):
'''constructor'''
QtGui.QMainWindow.__init__(self, parent)
self.setGeometry(0, 0, 650, 550)
self.setWindowTitle("My Example Application")
self.centerOnScreen()
def centerOnScreen (self):
'''centerOnScreen()
Centers the window on the screen.'''
resolution = QtGui.QDesktopWidget().screenGeometry()
self.move((resolution.width() / 2) - (self.frameSize().width() / 2),
(resolution.height() / 2) - (self.frameSize().height() / 2))
祝好运!
首先,我建议不要试图强制用户窗口位置,而是让系统的窗口管理器决定它应该去哪里。如果您真的坚持自己定位(也许您正在为一个信息亭编程),您可以在stackoverflow上的以前问题中找到一些信息。
这里讨论了一个稍微更优雅的计算方法。
在进行此计算时,重要的是在Qt调整大小后并且在屏幕上显示之前正确地完成。可能有助于创建一个一次性计时器并在计时器的槽中进行屏幕定位。
这个在Pyqt5中对我有效:
from PyQt5.QtWidgets import *
qtRectangle = self.frameGeometry()
centerPoint = QDesktopWidget().availableGeometry().center()
qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())
AttributeError: module 'PyQt5.QtGui' has no attribute 'QDesktopWidget'
- e-info128