Qpainter绘制半径渐变圆环
时间: 2023-06-13 12:04:41 浏览: 214
利用QPainter绘制各种图形
3星 · 编辑精心推荐
要使用QPainter绘制半径渐变圆环,可以按照以下步骤:
1. 创建一个圆形路径
```python
path = QPainterPath()
path.addEllipse(center, radius, radius)
```
其中,`center`是圆心坐标,`radius`是圆的半径。
2. 创建一个渐变
```python
gradient = QRadialGradient(center, radius, center)
gradient.setColorAt(0, QColor(255, 255, 255, 255))
gradient.setColorAt(0.5, QColor(255, 255, 255, 127))
gradient.setColorAt(1, QColor(255, 255, 255, 0))
```
其中,`center`是圆心坐标,`radius`是圆的半径,渐变从圆心到圆的边缘。
3. 设置渐变为画刷
```python
brush = QBrush(gradient)
painter.setBrush(brush)
```
4. 绘制路径
```python
painter.drawPath(path)
```
完整的代码如下:
```python
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MyWidget(QWidget):
def paintEvent(self, event):
painter = QPainter(self)
center = QPoint(self.width() // 2, self.height() // 2)
radius = min(center.x(), center.y()) - 20
path = QPainterPath()
path.addEllipse(center, radius, radius)
gradient = QRadialGradient(center, radius, center)
gradient.setColorAt(0, QColor(255, 255, 255, 255))
gradient.setColorAt(0.5, QColor(255, 255, 255, 127))
gradient.setColorAt(1, QColor(255, 255, 255, 0))
brush = QBrush(gradient)
painter.setBrush(brush)
painter.drawPath(path)
if __name__ == '__main__':
app = QApplication([])
widget = MyWidget()
widget.resize(400, 400)
widget.show()
app.exec_()
```
这样就可以绘制出一个半径渐变的圆环了。
阅读全文