2016-11-08 162 views
3

我想在QLabel上繪製一個自定義的Pixmap。我必須在一個圓圈中顯示圖像,並且該小部件在鼠標懸停上有動畫(例如,輪廓顏色突出顯示和屬性動畫)。我試圖在小部件的paintEvent內繪製整個圖像。但是性能下降速度是非常難以接受的。所以我製作了圖像緩存並在繪製事件中設置了像素圖,但圖像變得像素化。我究竟做錯了什麼? paintEvent中的相同功能可以繪製出高質量的圖像。如何使用QPainter高效地繪製圖像?

這是我的緩存像素圖

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中的第一個問題。對不起,如果有什麼是非常錯誤的。謝謝。

回答

1

這是問題,

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

無需調整圖像大小。這使它像素化! 提供全尺寸圖像解決了問題。