简体   繁体   English

PyQt5:如何单击按钮开始绘制?

[英]PyQt5: How to click a button to start the paint?

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: paintEvent()方法是由 Qt 内部调用的,它不应该直接调用,而是通过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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM