我通过在QPainter
函数中使用paintEvent
创建了一个矩形。以下是我的代码
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"))
如何从其他功能中更新矩形和文本内容(矩形内部)的颜色?
def updateRectanle(conditon):
if condition:
update_rectangle_color
update_rectangle_text
答案 0 :(得分:2)
您不应像已经知道的那样直接调用paintEvent()
,您应该做的就是告诉GUI您需要重新粉刷,我们可以使用方法repaint()
和update()
。第一种方法需要同步更新,第二种方法是异步更新,我更喜欢第二种情况。
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()