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:
from PySide6.QtCore import Qt, QPoint
from PySide6.QtGui import QPainter, QPen, QFont
from PySide6.QtWidgets import QWidget, QApplication
def paintEvent(self, event):
# create QPainter object
painter = QPainter(self)
# set pen color and width
pen = QPen(Qt.black, 2, Qt.SolidLine)
# set font and font size
font = QFont("Arial", 24)
# 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
# run the event loop
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.