The following code makes a button and a rectangle. I would like to change it, so that the rectangle is drawn when the button is clicked.
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_())
Thanks for your help!
the paintEvent()
method is called internally by Qt, it should not be called directly but through the update()
method, but in your case you want to do it when a certain condition is used, before that you must create a flag that indicates that it should be drawn, all of the above is implemented in the following code:
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)