PyQt5:在Qmovie中重新加载gif



我将如何在 PyQt5 中重新加载新的动画 gif 文件?

我想做什么:

  1. 负载测试.gif
  2. 游戏测试.gif
  3. 用另一个任意动画 GIF 覆盖原始 test.gif 文件
  4. 点击按钮时让Qmovie重新加载gif
  5. 显示新的 GIF

这是我为尝试此操作而设置的基本代码,但是单击按钮刷新不起作用:

import sys
from PyQt5.QtCore import Qt, QByteArray, QSettings, QTimer, pyqtSlot
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QSizePolicy, QVBoxLayout, QAction, QPushButton
from PyQt5.QtGui import QMovie
class GifPlayer(QWidget):
def __init__(self, title, parent=None):
QWidget.__init__(self, parent)
self.movie = QMovie("test.gif", QByteArray(), self)
size = self.movie.scaledSize()
self.setGeometry(200, 200, size.width(), size.height())
self.setWindowTitle(title)
self.movie_screen = QLabel()
self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.movie_screen.setAlignment(Qt.AlignCenter)        
main_layout = QVBoxLayout()
main_layout.addWidget(self.movie_screen)
self.setLayout(main_layout)
self.movie.setCacheMode(QMovie.CacheAll)
self.movie_screen.setMovie(self.movie)
self.movie.start()
self.movie.loopCount()
button = QPushButton('refresh gif', self)
button.setToolTip('This is an example button')
button.move(10,10)
button.clicked.connect(self.on_click)
@pyqtSlot()
def on_click(self):
self.movie_screen.setMovie(self.movie)
print("done")     
if __name__ == "__main__":  
app = QApplication(sys.argv)
player = GifPlayer("update this gif")
player.show()
sys.exit(app.exec_())

事实证明,这是一个从根本上简单的解决方案。错误是试图刷新movie_screen而不是电影本身。只需再次设置 QMovie 文件,让movie_screen重新显示它,然后开始电影。以下是更正后的代码:

gifFile = "test.gif"
class GifPlayer(QWidget):
def __init__(self, title, gifFile, parent=None):
QWidget.__init__(self, parent)
self.movie = QMovie(gifFile, QByteArray(), self)
size = self.movie.scaledSize()
self.setGeometry(200, 200, size.width(), size.height())
self.setWindowTitle(title)
self.movie_screen = QLabel()
self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.movie_screen.setAlignment(Qt.AlignCenter)
main_layout = QVBoxLayout()
main_layout.addWidget(self.movie_screen)
self.setLayout(main_layout)
self.movie.setCacheMode(QMovie.CacheAll)
self.movie_screen.setMovie(self.movie)
self.movie.start()
self.movie.loopCount()
button = QPushButton('refresh gif', self)
button.setToolTip('This is an example button')
button.move(10,10)
button.clicked.connect(self.on_click)
@pyqtSlot()
def on_click(self):
self.movie = QMovie(gifFile,QByteArray(), self)
self.movie_screen.setMovie(self.movie)
self.movie.start()
print("done")
if __name__ == "__main__":
app = QApplication(sys.argv)
player = GifPlayer("update this gif", gifFile)
player.show()
sys.exit(app.exec_())

on_click方法主要是需要改变的。

相关内容

  • 没有找到相关文章

最新更新