Jason
Jason

Reputation: 41

How to put the window in the top left corner with PyQt?

I'm trying to put my window in the top left corner by runing the following code:

import sys
from PyQt5 import QtGui
class MainWindow(QtGui.QWidget):

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

    def initUI(self):
        self.resize(640, 480)
        self.topLeft()
        self.show()

    def topLeft()(self):
        frameGm = self.frameGeometry()
        topLeftPoint = QApplication.desktop().availableGeometry().topLeft()
        frameGm.moveTopLeft(topLeftPoint)
        self.move(frameGm.topLeft())

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

if __name__ == '__main__':
    main()

But doing so, I get a gap between my window and the left-side of the screen like this :

enter image description here

Do you know where it comes from and how to prevent it?

Upvotes: 2

Views: 3694

Answers (1)

musicamante
musicamante

Reputation: 48231

This happens because when a window is shown the first time on the screen, some things (lots, actually) happen between show() and the moment where the window is actually mapped on the screen.

In order to achieve what you want, you need to delay the movement by some amount of time (usually, on "cycle" of the event loop is enough). Using a single shot QTimer with 1 timeout is normally fine.

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(640, 480)
        QTimer.singleShot(1, self.topLeft)
        self.show()

    def topLeft(self):
        # no need to move the point of the geometry rect if you're going to use
        # the reference top left only
        topLeftPoint = QApplication.desktop().availableGeometry().topLeft()
        self.move(topLeftPoint)

Upvotes: 2

Related Questions