prattom
prattom

Reputation: 1743

Updating color of an object created paintEvent from other function

I have created a rectangle by using QPainter in paintEvent function. Following is my code

def paintEvent(self, event):
    QWidget.paintEvent(self, event)
    painter = QPainter(self)
    pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)

    painter.setPen(QtCore.Qt.red)
    painter.setBrush(QtGui.QColor(200, 0, 0))
    rect = QRect(1450,325,380,498)
    painter.drawRect(rect)
    painter.setFont(QtGui.QFont('Consolas', 30))
    painter.setPen(QtGui.QColor(0, 0, 0))
    painter.drawText(QRect(1450,325,380,498), QtCore.Qt.AlignCenter, str("Welcome"))

How can I update the color of rectangle and text content(inside rectangle) from some other function?

def updateRectanle(conditon):
    if condition: 
        update_rectangle_color
        update_rectangle_text

Upvotes: 1

Views: 95

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

You should not call paintEvent() directly as you already know, what you should do is tell the GUI that you need a repaint for this we can use the method repaint() and update(). The first method requires updating synchronously, and in the case of the second asynchronously, I prefer the second case.

def __init__(self, foo_params):
    super(Foo_class, self).__init__(super_foo_params)
    self._text = "Welcome"
    self._rect_color = QtGui.QColor(200, 0, 0)

def paintEvent(self, event):
    super(Foo_class, self).paintEvent(event)
    painter = QPainter(self)
    pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)

    painter.setPen(QtCore.Qt.red)
    painter.setBrush(self._rect_color)
    rect = QRect(1450,325,380,498)
    painter.drawRect(rect)
    painter.setFont(QtGui.QFont('Consolas', 30))
    painter.setPen(QtGui.QColor(0, 0, 0))
    painter.drawText(QRect(1450,325,380,498), QtCore.Qt.AlignCenter, self._text)

def updateRectanle(conditon):
    if condition: 
        self._rect_color = new_color
        self._text = new_text
        self.update()

Upvotes: 2

Related Questions