如何在PyQt5中使用QMovie应用边界半径或以其他方式实现圆角效果?它似乎对QSS没有反应。尽管我不认为这是相关的,但无论如何这是我当前的代码,以使我有所了解:

image = QLabel()
image.setObjectName("rant-image")
movie = QMovie("image_cache/" + img_name)
image.setMovie(movie)
movie.start()


使用QSS:

QLabel#rant-image{
    border-radius: 5px;
}


我还尝试通过子类化QWidget来绘制每个paintEvent的当前像素图,但是什么也没有出现,并且像素图的尺寸为0:

invisible_pen = QPen()
invisible_pen.setWidth(0)
invisible_pen.setStyle(Qt.NoPen)


class RoundedMovie(QWidget):

    def __init__(self, movie, parent=None):
        QWidget.__init__(self, parent)
        self.movie = movie

    def setMovie(self, movie):
        self.movie = movie

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        pixmap = self.movie.currentPixmap()
        brush = QBrush(pixmap)
        rect = QRect(0, 0, pixmap.width() - 10, pixmap.height() - 10)
        painter.setPen(invisible_pen)
        painter.setBrush(brush)
        painter.drawRoundedRect(rect, 5, 5)


我也知道上述实现将无法正常工作,因为paintEvent的发生频率不足以按预期播放电影

最佳答案

一个可能的解决方案是实现QProxyStyle

from PyQt5 import QtCore, QtGui, QtWidgets

class RoundPixmapStyle(QtWidgets.QProxyStyle):
    def __init__(self, radius=10, *args, **kwargs):
        super(RoundPixmapStyle, self).__init__(*args, **kwargs)
        self._radius = radius

    def drawItemPixmap(self, painter, rectangle, alignment, pixmap):
        painter.save()
        pix = QtGui.QPixmap(pixmap.size())
        pix.fill(QtCore.Qt.transparent)
        p = QtGui.QPainter(pix)
        p.setBrush(QtGui.QBrush(pixmap))
        p.setPen(QtCore.Qt.NoPen)
        p.drawRoundedRect(pixmap.rect(), self._radius, self._radius)
        p.end()
        super(RoundPixmapStyle, self).drawItemPixmap(painter, rectangle, alignment, pix)
        painter.restore()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
    proxy_style = RoundPixmapStyle(radius=20, style=w.style())
    w.setStyle(proxy_style)
    movie = QtGui.QMovie("foo.gif")
    w.setMovie(movie)
    movie.start()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())


python - 具有边界半径的QMovie-LMLPHP

09-06 17:57