以下代码生成一个按钮和一个矩形。我想更改它,以便在单击按钮时绘制矩形。
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton
from PyQt5.QtGui import QPainter, QColor, QBrush
import sys
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setFixedSize(400, 400)
self.setWindowTitle('Colours')
self.btn = QPushButton("Paint", self)
self.btn.move(100, 100)
# self.btn.clicked.connect(self.paintEvent())
self.show()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawRectangles(qp)
qp.end()
def drawRectangles(self, qp):
col = QColor(0, 0, 0)
col.setNamedColor('#d4d4d4')
qp.setPen(col)
qp.setBrush(QColor(200, 0, 0))
qp.drawRect(10, 15, 90, 60)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
感谢您的帮助!
答案 0 :(得分:1)
Qt在内部调用paintEvent()
方法,不应该通过update()
方法直接调用它,但是在你的情况下你想在使用某个条件时执行它,在此之前你必须创建一个标志,表明它应该被绘制,所有上述内容都在以下代码中实现:
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
self.flag = False
def initUI(self):
self.setFixedSize(400, 400)
self.setWindowTitle('Colours')
self.btn = QPushButton("Paint", self)
self.btn.move(100, 100)
self.btn.clicked.connect(self.onClicked)
self.show()
def onClicked(self):
self.flag = True
self.update()
def paintEvent(self, e):
if self.flag:
qp = QPainter()
qp.begin(self)
self.drawRectangles(qp)
qp.end()
def drawRectangles(self, qp):
col = QColor(0, 0, 0)
col.setNamedColor('#d4d4d4')
qp.setPen(col)
qp.setBrush(QColor(200, 0, 0))
qp.drawRect(10, 15, 90, 60)