问题
I am trying to overlay some graphics(QtGraphicsView) on top of video player(QVideoWidget). i have already tried setting QtGraphicsView subclass stylesheets to transparent and background brush and none is working.
#self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30, 3)))
#self.setStyleSheet("background-color:rgba(0,0,0,0)")
#self.setStyleSheet("background:rgba(0,0,0,0)")
self.setStyleSheet("background:transparent")
self.setStyleSheet("background-color:transparent")
self.setStyleSheet("background-color:rgba(30,30,30,3)")
self.setStyleSheet("background:rgba(30,30,30,3)")
Actual Intentions is to easily crop a video (visual way). All other work is done regarding capturing events , doing math etc. this image explains situation pretty well. . At this point it feels, surely i am doing it wrong way, there must be some easier way in QtMultiMedia Components to draw on top of them. Any Ideas really appreciated.
回答1:
One possible solution is to use QGraphicsVideoItem instead of QVideoWidget and embed it in the QGraphicsView, then the other items can be made child of the QGraphicsVideoItem so that it is on top, besides the position of the new items will be related to the QGraphicsVideoItem.
import os
from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia, QtMultimediaWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self._scene = QtWidgets.QGraphicsScene(self)
self._gv = QtWidgets.QGraphicsView(self._scene)
self._videoitem = QtMultimediaWidgets.QGraphicsVideoItem()
self._scene.addItem(self._videoitem)
self._ellipse_item = QtWidgets.QGraphicsEllipseItem(QtCore.QRectF(50, 50, 40, 40), self._videoitem)
self._ellipse_item.setBrush(QtGui.QBrush(QtCore.Qt.green))
self._ellipse_item.setPen(QtGui.QPen(QtCore.Qt.red))
self._player = QtMultimedia.QMediaPlayer(self, QtMultimedia.QMediaPlayer.VideoSurface)
self._player.stateChanged.connect(self.on_stateChanged)
self._player.setVideoOutput(self._videoitem)
file = os.path.join(os.path.dirname(__file__), "small.mp4")
self._player.setMedia(QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(file)))
button = QtWidgets.QPushButton("Play")
button.clicked.connect(self._player.play)
self.resize(640, 480)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self._gv)
lay.addWidget(button)
@QtCore.pyqtSlot(QtMultimedia.QMediaPlayer.State)
def on_stateChanged(self, state):
if state == QtMultimedia.QMediaPlayer.PlayingState:
self._gv.fitInView(self._videoitem, QtCore.Qt.KeepAspectRatio)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
来源:https://stackoverflow.com/questions/53899740/how-to-draw-qtgraphicsview-on-top-of-qvideowidget-with-transparency