2016-06-09 106 views
2

上面的代碼奇怪地有問題。我不明白爲什麼,但如果我設置y窗口的大小超過923,窗口不放在屏幕中間。它會轉到屏幕的左上角。PyQt5奇怪的窗口位置問題

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

import sys 

class cssden(QMainWindow): 
    def __init__(self): 
     super().__init__() 


     self.mwidget = QMainWindow(self) 
     self.setWindowFlags(QtCore.Qt.FramelessWindowHint) 


     #size 
     self.setFixedSize(1100,923) # <--- set this 924 and more 
     self.center # <-- function that set the window middle of the screen 
     self.show() 

    def center(self): # <-- center function 
     qr = self.frameGeometry() 
     cp = QDesktopWidget().availableGeometry().center() 
     qr.moveCenter(cp) 
     self.move(qr.topLeft()) 

app = QApplication(sys.argv) 
app.setStyleSheet("QMainWindow{background-color: rgb(30,30,30);border: 1px solid black}") 

ex = cssden() 
sys.exit(app.exec_()) 

爲什麼?這是關於我的屏幕分辨率是1920x1080嗎?我只是不明白爲什麼這個號碼是923以及如何解決這個問題。

編輯:原來PyQt在窗口自動居中後,923爲什麼它要到屏幕的左上角?每個分辨率是否有默認數字?

+0

我注意到你實際上沒有調用'center()'。這可能是問題嗎? –

+0

@BrendanAbel不,在'923'下方,窗口位於屏幕的中心。看到'self.center' – GLHF

+0

@GLHF @BrendanAbel是正確的。儘管窗口可能會居中,但實際上並沒有在上面的代碼中調用self.center()。你只是獲得參考。你需要'self.center()'中的parens。 :-) – jszakmeister

回答

0

嘗試這種解決方案從這樣的回答:PyQt4 center window on active screen

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函數來確定鼠標當前處於活動狀態的屏幕爲 。然後它找到該監視器的屏幕幾何圖形和該屏幕的中心點。使用這種方法,即使監視器 的分辨率不同,您應該可以將窗口放置在屏幕的中心。