In this lesson we want to learn about Python PySide6 Draw Text, PySide6 provides QPainter class to perform custom drawing operations on paint device. In this lesson, we will explore how to draw text using QPainter, to follow this lesson, you should have basic understanding of Python programming and the PySide6 library. if you are new to PySide6, you may want to check out some introductory tutorials before continuing, or go back to the course and check the previous lessons.
This is an example code for drawing text in PySide6 using QPainter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
from PySide6.QtCore import Qt, QPoint from PySide6.QtGui import QPainter, QPen, QFont from PySide6.QtWidgets import QWidget, QApplication class MyWidget(QWidget): def __init__(self): super().__init__() def paintEvent(self, event): # create QPainter object painter = QPainter(self) # set pen color and width pen = QPen(Qt.black, 2, Qt.SolidLine) painter.setPen(pen) # set font and font size font = QFont("Arial", 24) painter.setFont(font) # set the position for the text text_pos = QPoint(100, 100) # draw the text painter.drawText(text_pos, "Hello GeeksCoders.com") if __name__ == '__main__': # create the application app = QApplication([]) # create an instance of our widget widget = MyWidget() # show the widget widget.show() # run the event loop app.exec() |
In this code we have defined custom widget MyWidget that inherits from QWidget. we override its paintEvent() method, which is called when the widget needs to be painted.
In paintEvent() method we have created QPainter object using the widget as the paint device. after that we set the pen color and width, the font and font size and the position for the text using the respective classes.
Finally, we call the drawText() method of the QPainter object to draw the text at the specified position.
Note that the paintEvent() method is called automatically when the widget is shown, and that the QApplication event loop is started to handle user events. also QPainter object is created and used within the paintEvent() method, and is destroyed automatically when the method returns.
Run the complete code and this will be the result.