I have developed a widget that draws a circle using QPainter. The test program creates the widget and then deletes it after 5 seconds. But the circle it drew remains. Shouldn't it disappear, or if not, how do I remove it (calling update() on the parent window has no effect)?
I expected the circle to disappear, but it doesn't. Here is the widget and test-code:
from __future__ import annotations
import typing
from PyQt6.QtGui import QPaintEvent, QPainter, QColor, QBrush
from PyQt6.QtWidgets import QWidget
from PyQt6.QtCore import Qt, QPoint, QPointF, QSize
class PlayerToken(QWidget):
SIZE = 12
def __init__(self, parent, colour):
super(PlayerToken, self).__init__(parent)
self.setMinimumSize(QSize(self.SIZE*2, self.SIZE*2))
self.colour = colour
self.update()
def move(self, where : QPoint):
centrePos = QPoint(where.x() - self.SIZE, where.y() - self.SIZE)
super().move(centrePos)
def paintEvent(self, event : QPaintEvent) -> None:
event.accept()
painter = QPainter(self)
painter.begin(self)
painter.translate(self.SIZE, self.SIZE)
painter.setBrush(QBrush(QColor(self.colour), Qt.BrushStyle.SolidPattern))
painter.drawEllipse(QPointF(0, 0), self.SIZE, self.SIZE)
painter.end()
painter = None
if __name__ == "__main__":
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtCore import QSize, QTimer
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__( *args, **kwargs)
self.setMinimumSize(QSize(400, 500))
self.playerToken = PlayerToken(self, 'red')
self.playerToken.move(QPoint(100, 300))
self.playerToken.show()
QTimer.singleShot(5*1000, self.Remove)
def Remove(self):
self.playerToken = None
del self.playerToken
self.update()
print('Remove exiting')
pass
app = QApplication([])
mainWindow = MainWindow()
mainWindow.show()
retCode = app.exec()