I have a QGraphicsPixmapItem that I want to rotate. If I use a button on the GUI to set the rotation, it rotates fine and is redrawn fine. If I have a separate thread execute the same command (setRotation), it rotates fine every time but doesn't always redraw the item. I know it rotates because if I drag a movable object over it, it will redraw underneath it. I have recreated this in a smaller program to demonstrate. If you start the timer, and the item disappears, drag the rect over it and it will appear. How do I force it to redraw (or repaint)?
from PySide6 import QtWidgets
from PySide6 import QtCore
from PySide6 import QtGui
import sys
import random
import time
import threading
class Window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(0, 0, 310, 250)
# Create 1 second timer for updating GUI
self.update_gui_thread = threading.Thread(target=self.start_update_timer)
self.create_ui()
self.show()
def rotate_random(self):
self.rotationItem.setRotation(random.randint(1, 359))
def start_update_timer(self):
while True:
self.rotationItem.setRotation(random.randint(1, 359))
time.sleep(2)
def create_ui(self):
self.scene = QtWidgets.QGraphicsScene(self)
self.rotationItem = self.scene.addPixmap(QtGui.QPixmap('c130_top.png'))
# set the origin for the transformation at the center of the pixmap
self.rotationItem.setTransformOriginPoint(self.rotationItem.boundingRect().center())
# ensure that the transformation is always antialiased
self.rotationItem.setTransformationMode(QtCore.Qt.TransformationMode.SmoothTransformation)
blue_brush = QtGui.QBrush(QtCore.Qt.GlobalColor.blue)
black_pen = QtGui.QPen(QtCore.Qt.GlobalColor.black)
black_pen.setWidth(1)
self.rect = self.scene.addRect(0, 0, 20, 20, black_pen, blue_brush)
self.rect.setTransformOriginPoint(self.rect.boundingRect().center())
self.rect.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable)
self.graphicsView = QtWidgets.QGraphicsView(self)
self.graphicsView.setGeometry(0, 0, 300, 200)
self.graphicsView.setScene(self.scene)
button = QtWidgets.QPushButton("Start Timer", self)
button.setGeometry(0, 200, 100, 50)
button.clicked.connect(self.update_gui_thread.start)
button2 = QtWidgets.QPushButton("Rotate Random", self)
button2.setGeometry(100, 200, 100, 50)
button2.clicked.connect(self.rotate_random)
app = QtWidgets.QApplication(sys.argv)
window = Window()
sys.exit(app.exec())