qframe 绘图_PyQt5利用QPainter绘制各种图形
时间: 2023-12-19 16:05:11 浏览: 156
PyQt5是Python语言的GUI编程工具包,其中包含了QPainter类,可以用来绘制各种图形。下面是一些常见的图形及其绘制方法:
1. 直线
```python
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt
pen = QPen(Qt.black, 2, Qt.SolidLine)
painter = QPainter()
painter.begin(self)
painter.setPen(pen)
painter.drawLine(0, 0, 100, 100)
painter.end()
```
2. 矩形
```python
from PyQt5.QtGui import QPainter, QPen, QBrush
from PyQt5.QtCore import Qt
pen = QPen(Qt.black, 2, Qt.SolidLine)
brush = QBrush(Qt.gray)
painter = QPainter()
painter.begin(self)
painter.setPen(pen)
painter.setBrush(brush)
painter.drawRect(0, 0, 100, 100)
painter.end()
```
3. 圆形
```python
from PyQt5.QtGui import QPainter, QPen, QBrush
from PyQt5.QtCore import Qt
pen = QPen(Qt.black, 2, Qt.SolidLine)
brush = QBrush(Qt.gray)
painter = QPainter()
painter.begin(self)
painter.setPen(pen)
painter.setBrush(brush)
painter.drawEllipse(0, 0, 100, 100)
painter.end()
```
4. 文字
```python
from PyQt5.QtGui import QPainter, QFont
from PyQt5.QtCore import Qt
font = QFont("Arial", 16)
painter = QPainter()
painter.begin(self)
painter.setFont(font)
painter.drawText(0, 0, "Hello PyQt5")
painter.end()
```
5. 多边形
```python
from PyQt5.QtGui import QPainter, QPen, QBrush
from PyQt5.QtCore import Qt, QPoint
pen = QPen(Qt.black, 2, Qt.SolidLine)
brush = QBrush(Qt.gray)
painter = QPainter()
painter.begin(self)
painter.setPen(pen)
painter.setBrush(brush)
points = [QPoint(0, 0), QPoint(50, 50), QPoint(100, 0)]
painter.drawPolygon(points)
painter.end()
```
以上只是一些常见的图形,QPainter还支持更多的绘制方法,比如曲线、扇形等等,具体可以参考官方文档。
阅读全文