为什么我的QGraphicsVideoItem在播放后会消失?可以在最后一帧暂停QMediaPlayer吗?

2024-06-02 07:25:31 发布

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

我编写了下面的(最小)代码,在QGraphicsScene中以QGraphicsVideoItem的形式显示视频。我关注的视频是动画,显示我想要向用户(example)显示的对象的创建。因此,每个视频的最后一帧是我希望永久保留在图形场景中的内容。但是,当QMediaPlayer播放完视频后,关联的图形视频项在Linux上不可见,在Windows上变为黑色。有没有办法防止这种行为?例如,是否可以在最后一个视频帧上暂停QMediaPlayer

我已经尝试从播放器获取视频持续时间,并在视频结束前运行计时器暂停视频,但持续时间仅在加载视频后的不可预见的时间内可用,因此这种技术会产生不可靠的结果

我的代码:

import os
os.environ['QT_MULTIMEDIA_PREFERRED_PLUGINS'] = 'windowsmediafoundation'
import sys

from PyQt5 import QtCore, QtMultimedia, QtMultimediaWidgets, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    """A window that displays a graphics scene in a central graphics view."""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.graphicsScene = QtWidgets.QGraphicsScene()
        self.graphicsScene.setSceneRect(0, 0, 800, 600)
        self.graphicsView = QtWidgets.QGraphicsView()
        self.graphicsView.setScene(self.graphicsScene)
        self.setCentralWidget(self.graphicsView)


class GraphicsVideoItem(QtMultimediaWidgets.QGraphicsVideoItem):
    """An item that displays a video file when added to a graphics scene."""
    def __init__(self, filepath):
        super().__init__()
        self.player = QtMultimedia.QMediaPlayer()
        self.player.setVideoOutput(self)
        self.player.setMedia(
            QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(filepath)))
        self.player.play()


def main():
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()

    # We display a video by adding it to the graphics scene.
    # The file test.mp4 is located in the same directory as this python file.
    # When the video finishes playing, it becomes invisible on Linux
    # and black on Windows.
    filepath = os.path.abspath("test.mp4")
    videoItem = GraphicsVideoItem(filepath)
    mainWindow.graphicsScene.addItem(videoItem)

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

Tags: importself视频initosdefsysscene