Reputation: 3
I'm using PyQt5 and I want to draw a text based on user's click on an existing pushbutton.
the text appears directly on Qwidget, I want the text to appear just after clicking the button. how to do it?
my code is like this:
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_())
Upvotes: 0
Views: 486
Reputation: 2111
First, set text to empty one:
self.text = ""
Then, it's important to create a button click event:
self.btn1 = QPushButton("Button 1", self)
self.btn1.clicked.connect(self.button_click)
Create a function to be called by clicking the button:
def button_click(self):
self.text = "Just For Test"
self.repaint()
Repaint will refresh your QPaint
Upvotes: 1