我试图使 QGraphicsScene 最大尺寸成为视频尺寸,因此如果我有文本并将其拖动到视频不是的任何位置,文本将不会出现,也不会显示滚动条。由于某种原因,场景仍然使用所有视图空间,即使我将其矩形设置为与视频相同。
import sys
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtGui import QResizeEvent, QShowEvent
from PySide6.QtWidgets import *
from PySide6.QtMultimediaWidgets import QGraphicsVideoItem
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput, QMediaMetaData
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.scene = QGraphicsScene()
self.view = QGraphicsView(self.scene)
self.video_widget = QGraphicsVideoItem()
self.scene.addItem(self.video_widget)
self.mediaPlayer = QMediaPlayer()
self.mediaPlayer.setVideoOutput(self.video_widget)
self.mediaPlayer.setSource(QUrl.fromLocalFile("potrait.mp4"))
self.video_widget.setSize(self.mediaPlayer.videoSink().videoSize())
self.text = QGraphicsTextItem("test")
self.text.setFlags(QGraphicsTextItem.ItemIsSelectable | QGraphicsTextItem.ItemIsMovable |
QGraphicsTextItem.ItemIsFocusable)
font = QFont()
font.setPointSize(100)
self.text.setFont(font)
self.scene.addItem(self.text)
layout = QVBoxLayout(self)
layout.addWidget(self.view)
self.setLayout(layout)
self.view.setScene(self.scene)
self.mediaPlayer.play()
def resizeFunc(self):
self.scene.setSceneRect(self.video_widget.boundingRect())
self.view.setSceneRect(0, 0, self.scene.sceneRect().width(), self.scene.sceneRect().height())
self.view.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)
def resizeEvent(self, event):
self.resizeFunc()
def showEvent(self, event):
self.resizeFunc()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
设置场景矩形不会使位于场景矩形之外的项目消失。正如文档所解释的那样:
“[场景的边界矩形]主要由 QGraphicsView 用来确定视图的默认可滚动区域,并由 QGraphicsScene 用来管理项目索引”。
一种可能是对项目进行clip绘画,但您需要它的子类:
class SceneClipTextItem(QGraphicsTextItem):
def paint(self, qp, opt, widget=None):
qp.save()
qp.setClipRect(self.scene().sceneRect())
super().paint(qp, opt, widget)
qp.restore()