pythonpyqtpyqt5qmediaplayerqvideowidget

PyQt5 - open QMediaplayer in new window and play video


This is probably comes down to basic python understanding, but I'm struggling with opening a video in a new window using PyQt5 and Python3.

When I run this code:

from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import  QApplication
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
import sys

app = QApplication(sys.argv)
w = QVideoWidget()
w.resize(300, 300)
w.move(0, 0)
w.show()
player = QMediaPlayer()
player.setMedia(QMediaContent(QUrl.fromLocalFile({inputVideo})))
player.setVideoOutput(w)
player.play()
sys.exit(app.exec_())

the window opens and plays the video file.

I tried to add this code to a class in my main program, and tried to call it, but it always fails.

What I want to achieve is to press a QPushbutton from the main GUI to open a new window and play the video in that new window.

As I said, it's probably basic python coding, but I guess I'm not there yet.

Your help is much appreciated!! Thanks!


Solution

  • You have to construct a QPushButton and connect its clicked slot to a function that shows and plays your video.

    (You have to setVideoOutput before you setMedia)

    from PyQt5.QtMultimediaWidgets import QVideoWidget
    from PyQt5.QtCore import QUrl
    from PyQt5.QtWidgets import QApplication, QPushButton
    from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
    import sys
    
    class VideoPlayer:
    
        def __init__(self):
            self.video = QVideoWidget()
            self.video.resize(300, 300)
            self.video.move(0, 0)
            self.player = QMediaPlayer()
            self.player.setVideoOutput(self.video)
            self.player.setMedia(QMediaContent(QUrl.fromLocalFile("./some_video_file.avi")))
    
        def callback(self):
            self.player.setPosition(0) # to start at the beginning of the video every time
            self.video.show()
            self.player.play()
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        v = VideoPlayer()
        b = QPushButton('start')
        b.clicked.connect(v.callback)
        b.show()
        sys.exit(app.exec_())