Learn how to add a widget to a window and move it around the screen in pyside6 with the true_property feature enabled.

Setting the absolute position of a widget in pyside6.

center window

For a pyside6 project I needed to move a widget around the screen. In my project, the feature true_property is enabled and this causes the method move not to be available on QWidgets.

A QWidget has a pos-attribute that you can use to set the position of a widget. For example:

label = QLabel("Hello")
label.set_parent(...)  #
label.show()
label.pos = QPoint(100, 200)  # Absolute positioning

There are two notable things here:

  1. You need to call label.set_parent(…). If you do not set the parent, all sprites in the following code will be presented as windows.
  2. Since you are not adding the label to a container like another widget or layout, you need to call label.show() manually.

Here is the full code for the animation above:

import sys
from PySide6.QtWidgets import QApplication
from PySide6.QtWidgets import QMainWindow
from PySide6.QtWidgets import QLabel
from PySide6.QtCore import QRect
from PySide6.QtCore import QPoint
from PySide6.QtWidgets import QStyle
from PySide6.QtCore import Qt
from PySide6.QtCore import QTime
from PySide6.QtCore import QSize
from PySide6.QtGui import QScreen
import math
from __feature__ import snake_case, true_property

app = QApplication(sys.argv)
mainwindow = QMainWindow()
mainwindow.geometry = QStyle.aligned_rect(Qt.LeftToRight, Qt.AlignCenter, QSize(400, 300), QApplication.primary_screen.available_geometry)
mainwindow.show()

sprites = []
for r in ["P", "Y", "T", "H", "O", "N"]:
label = QLabel(r)
label.set_parent(mainwindow)
label.show()
label.size = QSize(40, 40)
label.alignment = Qt.AlignCenter
label.setStyleSheet('background-color:#304; font-size:20px; font-weight:bold; color:#fff;')
sprites.append(label)

for i in range(500000):
angle = i / 20000;
j = 0
for s in sprites:
sprites[j].pos = QPoint(200 + math.sin(angle - j * .5) * 100, 120 + math.cos(angle - j * .3) * 100)
j = j + 1
QApplication.process_events()

app.exec_()

center window

Written by Loek van den Ouweland on 2021-01-09.
Questions regarding this artice? You can send them to the address below.