PyQt - Absolute positioning

Absolute positioning measures the position and size of each widget in pixels. When using absolute positioning, you should understand the following limitations:

  • Resizing the window does not change the size and position of the widget.
  • Applications may look different on various platforms.
  • Changing the font of the application can break the layout.
  • If you want to change the layout, you need to refresh it completely, which is very cumbersome.

We'll place two labels and two pushbutton widgets in an absolute positioning fashion.

Related course: Create Desktop Apps with Python PyQt5

Absolute positioning

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton

class MyApp(QWidget):

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

    def initUI(self):
        label1 = QLabel('Label1', self)
        label1.move(20, 20)
        label2 = QLabel('Label2', self)
        label2.move(20, 60)

        btn1 = QPushButton('Button1', self)
        btn1.move(80, 13)
        btn2 = QPushButton('Button2', self)
        btn2.move(80, 53)

        self.setWindowTitle('Absolute Positioning')
        self.setGeometry(300, 300, 400, 200)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Use the move() method to set the location of the widget. Adjust the position by setting the x and y coordinates of the label (label1, label2) and pushbutton (btn1, btn2).

pyqt absolute position python

The coordinate system starts at the upper left corner (0,0). The x coordinates grow from left to right, and the y coordinates grow from top to bottom.

Description

label1 = QLabel('Label1', self)
label1.move(20, 20)

Create one label and move it to x=20, y=20.

btn1 = QPushButton('Button1', self)
btn1.move(80, 13)

Create one pushbutton and move it to x=80, y=13.

Related course: Create Desktop Apps with Python PyQt5