What is the method for drawing graphics in PyQt5?

In PyQt5, the QPainter class can be used to draw various shapes such as lines, rectangles, and ellipses. Drawing shapes can be achieved by using a QPainter object in the paintEvent method of a QWidget. Here is an example code:

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt

class MyWidget(QWidget):
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setPen(QPen(Qt.black, 2, Qt.SolidLine))
        painter.drawLine(20, 20, 100, 100)
        painter.drawRect(120, 20, 80, 60)
        painter.drawEllipse(220, 20, 80, 60)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWidget()
    window.resize(400, 200)
    window.setWindowTitle('Drawing Example')
    window.show()
    sys.exit(app.exec_())

In the example above, we defined a custom window class MyWidget that inherits from QWidget, and used a QPainter object in its paintEvent method to draw a line, a rectangle, and an ellipse. Finally, we displayed the drawn graphics by creating an application object and showing the window.

 

More tutorials

What operating systems does PyQt5 support?(Opens in a new browser tab)

How to add a menu bar in PyQt5?(Opens in a new browser tab)

How to use databases in PyQt5?(Opens in a new browser tab)

What is the purpose of the QThread class in PyQt5?(Opens in a new browser tab)

What is the purpose of the QTimer class in PyQt5?(Opens in a new browser tab)

 

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds