python - 带边框半径的 QMovie
问题描述
如何在 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 - 无法将 JSON 文件导入 Python 文件
- angular - Angular CLI 进程没有开始监听 Angular 应用程序中的请求
- python - Google 的 Drive API 将下载的文件存储在哪里?
- html - 我使用了 Angular CLI:9.1.2,节点:12.16.2 和操作系统:linux x64 版本。我收到以下错误
- python - 我们如何才能让这个 python 代码更有效地运行巨大的文本文件?
- mysql - 要替换的sql查询
- sql - SQL添加从最新日期到当前日期的缺失日期
- javascript - 如何对更高范围的变量集进行解构赋值?
- express - 在 express 中将 api 数据发送回 vue 返回空对象
- python - 在基类的属性上使用 @property