python pyside6 QMediaPlayer 怎么放入布局中
时间: 2024-01-12 20:03:50 浏览: 320
基于QMediaplayer的播放器
4星 · 用户满意度95%
要将QMediaPlayer放入布局中,可以使用QVideoWidget。QVideoWidget是一个QWidget,可用于显示视频输出。以下是示例代码:
```python
from PySide6.QtCore import QUrl
from PySide6.QtGui import QPalette
from PySide6.QtMultimedia import QMediaPlayer, QMediaContent
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QSlider, QLabel, QStyle, QFileDialog, QSizePolicy, QSpacerItem, QStatusBar, QStyleOptionSlider, QStyleFactory, QVideoWidget
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建QWidget作为主窗口的中心部件
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
# 创建QMediaPlayer和QVideoWidget
self.media_player = QMediaPlayer(self)
video_widget = QVideoWidget(central_widget)
self.media_player.setVideoOutput(video_widget)
# 将QVideoWidget添加到布局中
vbox_layout = QVBoxLayout(central_widget)
vbox_layout.addWidget(video_widget)
# 创建控制按钮
control_button_layout = QHBoxLayout()
control_button_layout.setContentsMargins(0, 0, 0, 0)
control_button_layout.setSpacing(0)
self.play_button = QPushButton()
self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
self.play_button.clicked.connect(self.play_clicked)
control_button_layout.addWidget(self.play_button)
self.stop_button = QPushButton()
self.stop_button.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
self.stop_button.clicked.connect(self.stop_clicked)
control_button_layout.addWidget(self.stop_button)
vbox_layout.addLayout(control_button_layout)
# 创建进度条
self.position_slider = QSlider()
self.position_slider.setOrientation(Qt.Horizontal)
self.position_slider.setRange(0, 0)
self.position_slider.sliderMoved.connect(self.set_position)
vbox_layout.addWidget(self.position_slider)
# 创建标签
self.label = QLabel()
vbox_layout.addWidget(self.label)
# 创建状态栏
self.statusBar = QStatusBar(self)
self.setStatusBar(self.statusBar)
# 设置窗口大小和标题
self.setGeometry(100, 100, 640, 480)
self.setWindowTitle("QMediaPlayer Example")
# 打开文件
self.open_file()
def open_file(self):
# 打开文件
file_name, _ = QFileDialog.getOpenFileName(self, "Open file", ".", "Video Files (*.mp4 *.flv *.ts *.mts *.avi *.mov *.wmv)")
if file_name != '':
# 设置文件路径
media_content = QMediaContent(QUrl.fromLocalFile(file_name))
self.media_player.setMedia(media_content)
# 设置窗口标题
self.setWindowTitle("QMediaPlayer Example - " + file_name)
def play_clicked(self):
# 切换播放/暂停状态
if self.media_player.state() == QMediaPlayer.PlayingState:
self.media_player.pause()
else:
self.media_player.play()
def stop_clicked(self):
# 停止播放
self.media_player.stop()
def set_position(self, position):
# 设置播放进度
self.media_player.setPosition(position)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
在此示例中,我们使用QVBoxLayout将QVideoWidget添加到QWidget中,然后使用QHBoxLayout将控制按钮添加到QVBoxLayout中。最后,我们使用QVBoxLayout将QSlider和QLabel添加到QWidget中。请注意,我们使用QSpacerItem来添加一些空间,以便在布局中垂直对齐标签和QSlider。
阅读全文