Show QMainwindow in the middle of the screen

2019-05-29 07:18发布

I want show my project main window in the middle of the screen . when i call "self.show()" then the window show in the middle of the screen .

2条回答
地球回转人心会变
2楼-- · 2019-05-29 08:06

I know you have already solved it, but I make this answer for those who have the same question. I post it mainly because you asked for pyQt and the other answer is for Qt (C++). I found a workaround here: https://bashelton.com/2009/06/pyqt-center-on-screen/

Is so simple and works perfectly, I transmit it..

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

Good luck!

查看更多
聊天终结者
3楼-- · 2019-05-29 08:16

First I would recommend against trying to force a window position on your users and let the system's window manager decide where it should go. If you really insist on positioning it yourself (perhaps you are programming for a kiosk), you can find some information here in a previous question on stackoverflow.

A slightly more elegant calculation for doing this is discussed here.

When doing this calculation, it is important that it is done at the correct time, after Qt has resized everything and just before it is shown on screen. One method that might help is to create a one-shot timer and do the screen positioning in the slot for the timer.

查看更多
登录 后发表回答