Search code examples
pythonpyqtpyqt5qwidgetqpainter

Pyqt: How do I erase a text drawn at paintEvent?


I made a Roatatable Text class which inherits QWidget, and it works fine. But when I tried to erase this text with label.destroy(), it's not disappearing.

I tried to use QPainter.eraseRect(), changing painter to self.painter and executing label.painter.eraseRect(). But I failed.

Here's the code:

class RotatedText(QtWidgets.QWidget):
    def __init__(self, x, y, angle, text, color):
        QtWidgets.QWidget.__init__(self)
        # Setting variables...
        self.setGeometry(0, 0, 1920, 1080)
        # I did this because texts ain't showing if they're too far away from (0, 0)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.translate(self.x, self.y)
        painter.rotate(self.angle)
        painter.setPen(QtGui.QPen(QtGui.QColor(self.color_r, self.color_g, self.color_b)))
        painter.setFont(QtGui.QFont("나눔고딕", 20))
        painter.drawText(0, 0, self.text)
        painter.end()

class MainWindow(QtWidgets.QDialog):
    def __init__(self, parent=None):
        label = RotatedText(50, 50, 45, "hi", (0, 0, 0))
        label.setParent(self)
        label.show()

(Erased other codes not related to this)

Texts drawn with drawText() are on a widget, so I thought destroying widget could erase the texts, too... How do I erase it?

It's OK to replace this class with a new class inherits QLabel. It'll be lot more easy to use but I failed to make it, so I'm using this class.

p.s. Just erasing everything that has been painted is not appropriate solution for me because there are lots of texts and I want to erase just one.


Solution

  • Setting self.text = "" and calling update() worked. Big Thanks to eyllanesc!

    • I tried destroy() on other widgets, but it seems not to be 'destroyed'. Instead, deleteLater() worked. It worked on the widget I've made, too.