In PyQt, there are many ways to draw shapes and primitives on the screen. In this tutorial, we will focus on two common methods: using QPainter and QPainterPath.
Method 1: Using QPainter
Step 1: Import the necessary modules
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QPainter, QColor
from PyQt5.QtCore import Qt
Step 2: Create a custom widget class
class MyWidget(QWidget):
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
self.drawShapes(qp)
qp.end()
def drawShapes(self, qp):
qp.setBrush(QColor(200, 0, 0))
qp.drawRect(10, 15, 90, 60)
qp.setBrush(QColor(0, 200, 0))
qp.drawEllipse(130, 15, 90, 60)
qp.setBrush(QColor(0, 0, 200))
qp.drawPolygon([QPoint(230, 100), QPoint(130, 140), QPoint(330, 140)])
Step 3: Create the main application window
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 400, 200)
self.setWindowTitle('Drawing Primitives')
self.mywidget = MyWidget(self)
self.show()
Step 4: Run the application
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Method 2: Using QPainterPath
Step 1: Import the necessary modules
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QPainter, QPainterPath, QColor
Step 2: Create a custom widget class
class MyWidget(QWidget):
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
self.drawShapes(qp)
qp.end()
def drawShapes(self, qp):
path = QPainterPath()
path.addRect(10, 15, 90, 60)
qp.setBrush(QColor(200, 0, 0))
qp.drawPath(path)
path.addEllipse(130, 15, 90, 60)
qp.setBrush(QColor(0, 200, 0))
qp.drawPath(path)
path.moveTo(230, 100)
path.lineTo(130, 140)
path.lineTo(330, 140)
qp.setBrush(QColor(0, 0, 200))
qp.drawPath(path)
Step 3: Create the main application window
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 400, 200)
self.setWindowTitle('Drawing Primitives')
self.mywidget = MyWidget(self)
self.show()
Step 4: Run the application
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
In this tutorial, we covered two methods for drawing primitives in PyQt: using QPainter and QPainterPath. Both methods are powerful and flexible, allowing you to create complex shapes and designs with ease. Experiment with these techniques and see what kind of graphical masterpieces you can create!
А где запускается функция paintEvent?
Спасибо большое, друг. Твои видео помогли разобраться с PyQt и начать бахать на работе!