Search code examples
pythonpyqtpyqt5qgraphicsviewqvideowidget

Playing two videos side by side:Videos not showing


I'm trying to build a GUI that is made of multiple videos played in different positions on the window, all videos with alpha channels, as some overlap others, based on the instructions provided by the firmware of an external device.

I'm at the very beginning of the project, so all I want is to play two videos on the same screen and go from there. (although if you know a good example to share in regards of my final objective, that would be awesome too).

The hierarchy that I have seen that would work for this project would be a QMainWindow that contains a QGraphicsView, that contains a QGraphicsScene, that contains two QGraphicsVideoItem, being those the "output" of the QMediaPlayer. (Am I already taking the wrong way with this?)

A window opens, properly sized but no videos played. I've done many tests, such as adding a layout, changing the order of certain instructions, etc. But nothing.

import sys
from PyQt5.QtMultimedia import *
from PyQt5.QtMultimediaWidgets import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class VideoWindow(QMainWindow):
     def __init__(self):
        super(VideoWindow, self).__init__()
        self.setWindowTitle('QMediaPlayer TEST')
        self.resize(1920, 1080)

        self.vista = QGraphicsView(self)
        self.vista.setGeometry(QRect(0, 0, 1920, 1080))

        self.scene = QGraphicsScene(self.vista)
        self.scene.setSceneRect(0, 0, 1920, 1080)

        self.graphvitem1 = QGraphicsVideoItem()
        self.graphvitem2 = QGraphicsVideoItem()


        self.mediaPlayer1 = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer1.setVideoOutput(self.graphvitem1)
        self.mediaPlayer1.setMedia(QMediaContent(QUrl.fromLocalFile("/Users/elemental/Desktop/pyvids/v1na.mp4")))

        self.graphvitem1.setPos(100, 100)
        self.scene.addItem(self.graphvitem1)


        self.mediaPlayer2 = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer2.setVideoOutput(self.graphvitem2)
        self.mediaPlayer2.setMedia(QMediaContent(QUrl.fromLocalFile("/Users/elemental/Desktop/pyvids/v1na2.mp4")))

        self.graphvitem2.setPos(100, 500)
        self.scene.addItem(self.graphvitem2)


        self.mediaPlayer1.play()
        self.mediaPlayer2.play()
        self.vista.show()


if __name__ == '__main__':
     app = QApplication([])
     window = VideoWindow()
     window.show()
     sys.exit(app.exec_())

Solution

  • You didn't set the scene on the view.

    While the constructor of QGraphicsView can accept a QGraphicsScene (which will automatically be set on it), there's no such convenience for the QGraphicsScene constructor (since a scene can be shared among many views), and adding the view as argument will just set that view as a parent.

            self.scene = QGraphicsScene(self.vista)
            self.vista.setScene(self.scene)