如何使用qpaiter高效地绘制图像?

2024-06-10 06:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在QLabel上画一个定制的Pixmap。我必须在一个圆圈中显示图像,小部件在鼠标悬停时有动画(例如,轮廓颜色高亮显示,以及属性动画)。我尝试在widget的paintEvent中绘制整个图像。但是性能下降的速度是不可接受的。所以我做了图像缓存并在paint事件中设置了pixmap,但是图像被像素化了。我做错什么了?paintEvent中的相同函数可以绘制高质量的图像。在

这就是我缓存pixmap的方法

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

这就是我在画师内部设置像素贴图的方法

^{pr2}$

我不是专业的开发者,只是自学成才。这是我在stackoverflow中的第一个问题。如果出了什么大问题,很抱歉。谢谢。在


Tags: textrect图像imageselfwidthoptionpainter
1条回答
网友
1楼 · 发布于 2024-06-10 06:32:53

这就是问题所在

resizedImage = srcImage.scaled(self.width(), self.height(),
                                   qc.Qt.KeepAspectRatio,
                                   qc.Qt.SmoothTransformation)

无需调整图像大小。这使它像素化了! 提供全尺寸图像解决了这个问题。在

相关问题 更多 >