我想在QLabel上绘制一个自定义的Pixmap。我必须以圆形显示图像,并且小部件在鼠标悬停时具有动画(例如,轮廓颜色突出显示,以及属性动画)。我尝试在widget的paintEvent中绘制整个图像。但性能下降率是非常不可接受的。所以我已经制作了图像缓存并在paint事件中设置像素图,但图像变得像素化。我究竟做错了什么? paintEvent中的相同功能可以绘制高质量的图像。
这是我如何缓存像素图
def fancyDraw(self, outlinePen):
hasValidImage = self._validateImage(self.image)
option = qg.QStyleOption()
option.initFrom(self)
x = option.rect.x()
y = option.rect.y()
width = option.rect.width() * self.radius
if not hasValidImage and self.shortName:
srcImage = qg.QPixmap(200, 200)
srcImage.fill(qc.Qt.transparent)
painter = qg.QPainter(srcImage)
# painter.begin()
painter.setRenderHint(qg.QPainter.Antialiasing)
painter.setBrush(self._brushText)
painter.setPen(self._penClear)
text_path = qg.QPainterPath()
text_width = self.font_metrics.width(self.shortName)
text_height = self.font().pointSize()
text_path.addText((200 - text_width) / 2,
(200 - ((200 - text_height)) / 2) - 1,
self.font(), self.shortName)
painter.drawPath(text_path)
painter.end()
else:
srcImage = qg.QPixmap(qc.QString(self.image))
if srcImage.isNull():
logger.error("Failed to load image %s" % self.image)
resizedImage = srcImage.scaled(self.width(), self.height(),
qc.Qt.KeepAspectRatio,
qc.Qt.SmoothTransformation)
pixmap = qg.QPixmap(width, width)
pixmap.fill(qg.QColor("transparent"))
imgPainter = qg.QPainter(pixmap)
imgPainter.setRenderHint(qg.QPainter.Antialiasing)
clip = qg.QPainterPath()
clip.addEllipse(x + 1, y + 1, width - 2, width - 2)
imgPainter.setClipPath(clip)
imgPainter.drawPixmap(0, 0, width, width, resizedImage)
imgPainter.end()
painter = qg.QPainter(pixmap)
painter.setRenderHint(qg.QPainter.Antialiasing)
painter.setPen(outlinePen)
painter.drawEllipse(x + 1, y + 1, width - 2, width - 2)
painter.end()
return pixmap
这就是我在画家中设置像素图的方法
self.normalPaint = self.fancyDraw(self._penBorder)
self.hoverPaint = self.fancyDraw(self._penBorder)
def paintEvent(self, event):
painter = qg.QPainter(self)
painter.drawPixmap(qc.QRect(self.x(), self.y(), self.width(), self.width()),
self.normalPaint)
我不是专业开发人员,只是自学成才。这是我在stackoverflow中的第一个问题。对不起,如果出现严重错误的话。感谢。
答案 0 :(得分:1)
这就是问题,
resizedImage = srcImage.scaled(self.width(), self.height(),
qc.Qt.KeepAspectRatio,
qc.Qt.SmoothTransformation)
无需调整图像大小。这使它像素化! 提供全尺寸图像解决了这个问题。