gpt4 book ai didi

python - 如何使用pyqt4创建圆形图像?

转载 作者:行者123 更新时间:2023-12-02 03:01:36 25 4
gpt4 key购买 nike

这里我写了这段代码但没有工作:

import sys
from PyQt4 import QtGui, QtCore

class CricleImage(QtCore.QObject):
def __init__(self):
super(CricleImage, self).__init__()

self.pix = QtGui.QGraphicsPixmapItem(QtGui.QPixmap("bird(01).jpg"))

#drawRoundCircle
rect = self.pix.boundingRect()
self.gri = QtGui.QGraphicsRectItem(rect)
self.gri.setPen(QtGui.QColor('red'))


if __name__ == '__main__':

myQApplication = QtGui.QApplication(sys.argv)

IMG = CricleImage()
#scene
scene = QtGui.QGraphicsScene(0, 0, 400, 300)
scene.addItem(IMG.pix)
#view
view = QtGui.QGraphicsView(scene)
view.show()
sys.exit(myQApplication.exec_())

最佳答案

一种可能的解决方案是覆盖QGraphicsPixmapItem的paint()方法并使用setClipPath来限制绘画区域:

from PyQt4 import QtCore, QtGui


class CirclePixmapItem(QtGui.QGraphicsPixmapItem):
@property
def radius(self):
if not hasattr(self, "_radius"):
self._radius = 0
return self._radius

@radius.setter
def radius(self, value):
if value >= 0:
self._radius = value
self.update()

def paint(self, painter, option, widget=None):
painter.save()
rect = QtCore.QRectF(QtCore.QPointF(), 2 * self.radius * QtCore.QSizeF(1, 1))
rect.moveCenter(self.boundingRect().center())
path = QtGui.QPainterPath()
path.addEllipse(rect)
painter.setClipPath(path)
super().paint(painter, option, widget)
painter.restore()


if __name__ == "__main__":
import sys

app = QtGui.QApplication(sys.argv)

pixmap = QtGui.QPixmap("logo.jpg")

scene = QtGui.QGraphicsScene()
view = QtGui.QGraphicsView(scene)
view.setRenderHints(
QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform
)

it = CirclePixmapItem(pixmap)
scene.addItem(it)

it.radius = pixmap.width() / 2

view.show()
sys.exit(app.exec_())

enter image description here

更新:

# ...
view = QtGui.QGraphicsView(
scene, <b>alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft</b>
)
# ...
view.show()
<b>it.setPos(80, 80)</b>
sys.exit(app.exec_())

关于python - 如何使用pyqt4创建圆形图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com