Python 使用PyQt绘制

Python 使用PyQt绘制,python,pyqt,pyqt5,Python,Pyqt,Pyqt5,我使用的是PyQt5,我想根据用户对现有按钮的点击来绘制文本 文本直接显示在Qwidget上,我希望文本在单击按钮后立即显示。 怎么做 我的代码如下: import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class Example(QWidget): def __init__(self): super().__init__()

我使用的是PyQt5,我想根据用户对现有按钮的点击来绘制文本

文本直接显示在Qwidget上,我希望文本在单击按钮后立即显示。 怎么做

我的代码如下:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *



class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.text = "Just For Test"

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Drawing text')
        self.btn1 = QPushButton("Button 1", self)
        self.btn1.move(10, 10)
        self.show()
    def paintEvent(self,event):
        qp = QPainter()
        qp.begin(self)
        self.drawText(event, qp)
        qp.end()



    def drawText(self, event, qp):
        qp.setPen(QColor(168, 34, 3))
        qp.setFont(QFont('Decorative', 10))
        qp.drawText(event.rect(), Qt.AlignCenter, self.text)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

首先,将文本设置为空:

self.text = ""
然后,创建按钮单击事件非常重要:

self.btn1 = QPushButton("Button 1", self)
self.btn1.clicked.connect(self.button_click)
通过单击按钮创建要调用的函数:

def button_click(self):
    self.text = "Just For Test"
    self.repaint()
重新绘制将刷新您的
QPaint