pyqt5 QPainter
时间: 2023-12-11 19:46:03 浏览: 89
QPainter is a class in PyQt5 that provides a set of painting methods that can be used to draw on widgets, such as windows, buttons, and labels. It allows you to create custom graphics and visuals for your PyQt5 applications.
Here are some common methods used in QPainter:
- begin(): This method starts the painting process and specifies the device to be painted on.
- end(): This method ends the painting process and releases the device.
- setPen(): This method sets the pen color, width, and style used for drawing lines and outlines.
- setBrush(): This method sets the brush color and style used for filling shapes.
- drawText(): This method draws text on the widget.
- drawLine(): This method draws a line on the widget.
- drawRect(): This method draws a rectangle on the widget.
- drawEllipse(): This method draws an ellipse on the widget.
- drawArc(): This method draws an arc on the widget.
To use QPainter, you need to create a QPainter object and call its methods to draw on the widget. Here's an example:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QColor, QBrush
class MyWidget(QWidget):
def paintEvent(self, event):
painter = QPainter(self)
painter.setPen(QColor(255, 0, 0))
painter.setBrush(QBrush(QColor(255, 255, 0)))
painter.drawRect(10, 10, 100, 100)
painter.drawText(50, 50, "Hello PyQt5")
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
```
This code creates a custom widget that draws a red rectangle with a yellow fill and some text. The paintEvent() method is called whenever the widget needs to be repainted, and it creates a QPainter object to draw on the widget. The setPen() and setBrush() methods are used to set the pen and brush colors, and the drawRect() and drawText() methods are used to draw the rectangle and text, respectively.
阅读全文