Absolute positioning

The absolute positioning method places each widget by setting its location and size in pixels. When using the absolute layout method, make sure that you understand the following limitations:

  • Even if you resize the size of the window, the position and size of the widget does not change.

  • The application may look different in various platforms.

  • Changing the font of an application can damage the layout.

  • If you want to change the layout, you have to start from scratch and this is very bothersome.


We’ll place two labels and two push button widgets with absolute positioning.


Example

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 move() method to set the widget’s position. Set the x,y coordinates of the labels(label1, label2) and push buttons(btn1, btn2) to adjust the position.

The coordinate system starts at the top left corner. The x coordinates increases from left to right, and the y coordinates increases from top to bottom.


Description

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

Make a label and move it to x=20, y=20.


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

Make a push button and move it to x=80, y=13.


Results

../_images/3_1_absolute_positioning.png ../_images/3_1_absolute_positioning_mac.png

Figure 4-1. Absolute positioning.


Prev/Next

Next :