pyqt本来播放视频能显示,后来不能显示,最终排查,找到原因:
self.setAttribute(Qt.WA_TranslucentBackground, True)
后来查了一下,这句代码的意思是让背景透明。
顺便贴上其他常见功能设置。
desktop_geometry = QtWidgets.QApplication.desktop() # 获取屏幕大小
main_window_width = desktop_geometry.width() # 屏幕的宽
main_window_height = desktop_geometry.height() # 屏幕的高
rect = self.geometry() # 获取窗口界面大小
window_width = rect.width() # 窗口界面的宽
window_height = rect.height() # 窗口界面的高
x = (main_window_width - window_width) // 2 # 计算窗口左上角点横坐标
y = (main_window_height - window_height) // 2 # 计算窗口左上角点纵坐标
self.setGeometry(x, y, window_width, window_height) # 设置窗口界面在屏幕上的位置
# 无边框以及背景透明一般不会在主窗口中用到,一般使用在子窗口中,例如在子窗口中显示gif提示载入信息等等
self.setWindowFlags(Qt.FramelessWindowHint) # 无边框
self.setAttribute(Qt.WA_TranslucentBackground) # 背景透明
本文调研了其他播放ok的示例代码:
示例1:
如果播放不了,需要安装LAVFilters-xxx-Installer.exe
下载地址:
https://github.com/jacke121/VideoPlayer_PyQt5
LAVFilters-0.74.1-Installer.exe
import sys
from PyQt5 import QtCore, QtGui, QtWidgets,QtMultimedia,QtMultimediaWidgets
from PyQt5.QtWidgets import QApplication,QMainWindow,QAbstractItemView,QTableWidgetItem
from PyQt5.QtCore import Qt,QRect
from PyQt5.QtCore import QTimer
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia, QtMultimediaWidgets
from PyQt5.QtWidgets import QAbstractItemView, QTableWidgetItem, QApplication
class SubBox():
def __init__(self, Form):
self.line1 = QtWidgets.QLabel(Form)
self.line1.setObjectName("line1")
self.line1.setStyleSheet("QLabel{background-color:rgba(55, 255, 55, 100%);border:none;}")
self.line2 = QtWidgets.QLabel(Form)
self.line2.setObjectName("line2")
self.line2.setStyleSheet("QLabel{background-color:rgba(55, 255, 55, 100%);border:none;}")
self.line3 = QtWidgets.QLabel(Form)
self.line3.setObjectName("line3")
self.line3.setStyleSheet("QLabel{background-color:rgba(55, 255, 55, 100%);border:none;}")
self.line4 = QtWidgets.QLabel(Form)
self.line4.setObjectName("line4")
self.line4.setStyleSheet("QLabel{background-color:rgba(55, 255, 55, 100%);border:none;}")
def setParameters(self, x, y, width, height):
self.line1.setGeometry(QtCore.QRect(x, y, width, 1))
self.line2.setGeometry(QtCore.QRect(x, y + height, width, 1))
self.line3.setGeometry(QtCore.QRect(x, y, 1, height))
self.line4.setGeometry(QtCore.QRect(x + width, y, 1, height))
class VideoView(QtMultimediaWidgets.QVideoWidget): # 包含在视频上画框的功能
def __init__(self, Form):
super(VideoView, self).__init__(Form)
self.x0 = 0
self.y0 = 0
self.x1 = 0
self.y1 = 0
self.flag = False
self.SubtitleBox = SubBox(Form)
self.SubtitleBox.setParameters(0, 0, 0, 0)
# 鼠标点击事件
def mousePressEvent(self, event):
self.flag = True
self.x0 = event.x() + self.x()
self.y0 = event.y() + self.y()
self.SubtitleBox.setParameters(0, 0, 0, 0)
# 鼠标释放事件
def mouseReleaseEvent(self, event):
self.flag = False
self.update()
# 鼠标移动事件
def mouseMoveEvent(self, event):
if self.flag:
self.x1 = event.x() + self.x()
self.y1 = event.y() + self.y()
self.SubtitleBox.setParameters(self.x0, self.y0, self.x1 - self.x0, self.y1 - self.y0)
class Ui_PlayerForm(object):
def setupUi(self, PlayerForm):
PlayerForm.setObjectName("PlayerForm")
desktop = QApplication.desktop()
PlayerForm.resize(desktop.width() - 200, desktop.height() - 100)
self.vw = VideoView(PlayerForm)
self.vw.setGeometry(QtCore.QRect(10, 10, 1280, 720))
self.vw.setObjectName("graphicsView")
self.vw.show()
self.player = QtMultimedia.QMediaPlayer()
self.player.setVideoOutput(self.vw)
self.splitter = QtWidgets.QSplitter(PlayerForm)
self.splitter.setGeometry(QtCore.QRect(500, 780, 250, 30))
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setObjectName("splitter")
self.PauseButton = QtWidgets.QPushButton(self.splitter)
self.PauseButton.setObjectName("Pause")
self.PlayButton = QtWidgets.QPushButton(self.splitter)
self.PlayButton.setObjectName("Play")
self.StopButton = QtWidgets.QPushButton(self.splitter)
self.StopButton.setObjectName("Stop")
self.splitter_2 = QtWidgets.QSplitter(PlayerForm)
self.splitter_2.setGeometry(QtCore.QRect(500, 820, 250, 30))
self.splitter_2.setOrientation(QtCore.Qt.Horizontal)
self.splitter_2.setObjectName("splitter_2")
self.SubStart = QtWidgets.QPushButton(self.splitter_2)
self.SubStart.setObjectName("SubStart")
self.SubEnd = QtWidgets.QPushButton(self.splitter_2)
self.SubEnd.setObjectName("SubEnd")
self.SubConfirm = QtWidgets.QPushButton(self.splitter_2)
self.SubConfirm.setObjectName("OK")
self.splitter_3 = QtWidgets.QSplitter(PlayerForm)
self.splitter_3.setGeometry(QtCore.QRect(505, 850, 160, 30))
self.splitter_2.setOrientation(QtCore.Qt.Horizontal)
self.splitter_2.setObjectName("splitter_3")
self.StartTime = QtWidgets.QLabel(self.splitter_3)
self.StartTime.setObjectName("StartTime")
self.EndTime = QtWidgets.QLabel(self.splitter_3)
self.EndTime.setObjectName("EndTime")
self.ProgressBar = QtWidgets.QSlider(PlayerForm)
self.ProgressBar.setGeometry(QtCore.QRect(10, 740, 1280, 20))
self.ProgressBar.setOrientation(QtCore.Qt.Horizontal)
self.ProgressBar.setObjectName("ProgressBar")
self.FileOpen = QtWidgets.QPushButton(PlayerForm)
self.FileOpen.setGeometry(QtCore.QRect(10, 800, 75, 30))
self.FileOpen.setObjectName("FileOpen")
self.PlayTime = QtWidgets.QLabel(PlayerForm)
self.PlayTime.setGeometry(QtCore.QRect(20, 770, 55, 20))
self.PlayTime.setObjectName("0.00")
# 表格
self.TimeTable = QtWidgets.QTableWidget(PlayerForm)
self.TimeTable.setGeometry(QtCore.QRect(1300, 10, 220, 750))
self.TimeTable.setObjectName("TimeTable")
self.TimeTable.setColumnCount(2)
self.TimeTable.setRowCount(0)
# self.TimeTable.setColumnWidth(0,88)
# self.TimeTable.setColumnWidth(1,88)
self.TimeTable.setShowGrid(True)
self.TimeTable.setHorizontalHeaderLabels(['Start', 'End'])
self.TimeTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.DelLine = QtWidgets.QPushButton(PlayerForm)
self.DelLine.setGeometry(QtCore.QRect(1370, 780, 75, 25))
self.DelLine.setObjectName("DelLine")
self.SaveLine = QtWidgets.QPushButton(PlayerForm)
self.SaveLine.setGeometry(QtCore.QRect(1370, 820, 75, 25))
self.SaveLine.setObjectName("SaveLine")
self.retranslateUi(PlayerForm)
QtCore.QMetaObject.connectSlotsByName(PlayerForm)
def retranslateUi(self, PlayerForm):
_translate = QtCore.QCoreApplication.translate
PlayerForm.setWindowTitle(_translate("PlayerForm", "Form"))
self.PlayButton.setText(_translate("PlayerForm", "Play"))
self.StopButton.setText(_translate("PlayerForm", "Stop"))
self.PauseButton.setText(_translate("PlayerForm", "Pause"))
self.FileOpen.setText(_translate("PlayerForm", "OPEN"))
self.SubStart.setText(_translate("PlayerForm", "SubStart"))
self.SubEnd.setText(_translate("PlayerForm", "SubEnd"))
self.SubConfirm.setText(_translate("PlayerForm", "SubConfirm"))
self.StartTime.setText(_translate("PlayerForm", ""))
self.EndTime.setText(_translate("PlayerForm", ""))
self.PlayTime.setText(_translate("PlayerForm", "TextLabel"))
self.DelLine.setText(_translate("Form", "DelLine"))
self.SaveLine.setText(_translate("Form", "SaveLine"))
class MyMainForm(QMainWindow,Ui_PlayerForm):
def __init__(self, parent=None):
super(MyMainForm,self).__init__(parent)
self.setupUi(self)
self.setMinimumSize(1530/2,900/2)
self.PauseButton.clicked.connect(self.VideoPause)
self.PlayButton.clicked.connect(self.VideoPlay)
self.StopButton.clicked.connect(self.VideoStop)
self.FileOpen.clicked.connect(self.OpenVideo)
self.SubStart.clicked.connect(self._SubStart)
self.SubEnd.clicked.connect(self._SubEnd)
self.SubConfirm.clicked.connect(self._SubConfirm)
self.timer1=QTimer(self)
self.timer1.timeout.connect(self.TimeText)
self.timer2=QTimer(self)
self.timer2.timeout.connect(self.TimeBar)
self.ProgressBar.sliderPressed.connect(self.SliderPre)
self.ProgressBar.sliderReleased.connect(self.SliderRel)
self.ProgressBar.sliderMoved.connect(self.SliderMov)
self.TimeTable.setFocusPolicy(Qt.NoFocus)
self.DelLine.clicked.connect(self.DeleteLine)
self.SaveLine.clicked.connect(self.SaveSubTimeline)
self.setFocusPolicy(Qt.ClickFocus) #通过鼠标点击可以转移焦点。
self.FileName=""
self.OpenVideo()
self.ProgressBar.setMinimum(0)
self.ProgressBar.setMaximum(10000)
self.VideoStatus=1
self.SubData=[]
self.SubStartPoint=0
self.SubEndPoint=0
self.SubNum=1
def resizeEvent(self,evt): #当窗口大小改变时触发
self.vw.setGeometry(self.width()*10/1530,self.height()*10/900,self.width()*1280/1530,self.height()*720/900)
self.splitter.setGeometry(self.width()*500/1530,self.height()*780/900,self.width()*250/1530,self.height()*30/900)
self.splitter_2.setGeometry(self.width()*500/1530,self.height()*820/900,self.width()*250/1530,self.height()*30/900)
self.splitter_3.setGeometry(self.width()*505/1530,self.height()*850/900,self.width()*160/1530,self.height()*30/900)
self.ProgressBar.setGeometry(self.width()*10/1530,self.height()*740/900,self.width()*1280/1530,self.height()*20/900)
self.FileOpen.setGeometry(self.width()*10/1530,self.height()*800/900,self.width()*75/1530,self.height()*30/900)
self.PlayTime.setGeometry(self.width()*20/1530,self.height()*770/900,self.width()*55/1530,self.height()*20/900)
self.TimeTable.setGeometry(self.width()*1300/1530,self.height()*10/900,self.width()*220/1530,self.height()*750/900)
self.DelLine.setGeometry(self.width()*1370/1530,self.height()*780/900,self.width()*75/1530,self.height()*25/900)
self.SaveLine.setGeometry(self.width()*1370/1530,self.height()*820/900,self.width()*75/1530,self.height()*25/900)
def OpenVideo(self):
File=QtWidgets.QFileDialog.getOpenFileUrl()[0]
if File.fileName()!='':
self.player.setMedia(QtMultimedia.QMediaContent(File)) #打开视频,获得将要播放的视频的路径。
self.timer1.start(100)
self.timer2.start(100)
self.VideoPlay()
self.setWindowTitle(File.fileName())
self.FileName=File.fileName()
print(self.FileName)
def VideoPause(self):
self.player.pause()
self.vw.setFocus()#将焦点转移至视频播放页面方便监听键盘的空格键事件。
pass
def VideoPlay(self):
self.player.play()
self.vw.setFocus()#将焦点转移至视频播放页面方便监听键盘的空格键事件。
pass
def VideoStop(self):
self.player.stop()
self.vw.setFocus()#将焦点转移至视频播放页面方便监听键盘的空格键事件。
pass
def TimeText(self):
t=self.player.position()
self.PlayTime.setNum(t/1000)
#进度条部分
def SliderPre(self):
self.timer2.stop()
if self.player.state()==1:
self.player.pause()
self.VideoStatus=1
elif self.player.state()==2:
self.VideoStatus=2
pass
def SliderRel(self):
self.timer2.start(100)
if self.VideoStatus==1:
self.player.play()
if self.VideoStatus==2:
self.player.pause()
self.vw.setFocus()
pass
def SliderMov(self):
pos=self.ProgressBar.value()
self.player.setPosition(int(pos/10000*self.player.duration()))
pass
def TimeBar(self):
t=self.player.position()
if self.player.duration()!=0:
self.ProgressBar.setValue(int(t/self.player.duration()*10000))
def _SubStart(self):
self.SubStartPoint=self.player.position()
self.StartTime.setText(str(self.SubStartPoint))
self.vw.setFocus()
pass
def _SubEnd(self):
self.SubEndPoint=self.player.position()
self.EndTime.setText(str(self.SubEndPoint))
self.vw.setFocus()
pass
def _SubConfirm(self):
if self.SubEndPoint>self.SubStartPoint:
self.SubData.append([self.SubStartPoint,self.SubEndPoint,self.vw.x0+self.vw.x(),self.vw.y0-self.vw.y(),\
self.vw.x1+self.vw.x(),self.vw.y1-self.vw.y(),self.vw.width(),self.vw.height()])
row = self.TimeTable.rowCount()
self.TimeTable.insertRow(row)
item_start=QTableWidgetItem(str(self.SubStartPoint))
item_end=QTableWidgetItem(str(self.SubEndPoint))
self.TimeTable.setItem(row,0,item_start)
self.TimeTable.setItem(row,1,item_end)
self.SubNum+=1
self.vw.setFocus()
pass
def DeleteLine(self):
try:
row = self.TimeTable.selectedItems()[0].row() #获取选中文本所在的行
column = self.TimeTable.selectedItems()[0].column() #获取选中文本所在的列
self.TimeTable.removeRow(row)
del(self.SubData[row])
self.vw.setFocus()
except:
pass
def SaveSubTimeline(self):
print(self.FileName)
with open(self.FileName+".csv","w") as f:
f.write("StartTime,EndTime,x0,y0,x1,y1,width,height,\n")
with open(self.FileName+".csv","a") as f:
for data in self.SubData:
f.write(str(data[0])+","+str(data[1])+","+str(data[2])+","+str(data[3])+","+str(data[4])+\
","+str(data[5])+","+str(data[6])+","+str(data[7])+",\n")
pass
def keyPressEvent(self,evt):
#print(evt.key())
if evt.key()==Qt.Key_Space and self.player.state()==1:
self.player.pause()
elif evt.key()==Qt.Key_Space and self.player.state()==2:
self.player.play()
elif evt.key()==Qt.Key_Right:
self.player.setPosition(self.player.position()+50)
elif evt.key()==Qt.Key_Left:
self.player.setPosition(self.player.position()-50)
elif evt.key()==Qt.Key_Up:
self.player.setPosition(self.player.position()+250)
elif evt.key()==Qt.Key_Down:
self.player.setPosition(self.player.position()-250)
pass
if __name__=="__main__":
app=QApplication(sys.argv)
mywin=MyMainForm()
mywin.show()
sys.exit(app.exec_())
方法2:opencv读取视频,pyqt显示视频帧图片,测试ok
参考:https://blog.csdn.net/sxj731533730/article/details/106029646
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import cv2
import math
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Ui_MainWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Ui_MainWindow, self).__init__(parent)
self.num = 1;
# self.face_recong = face.Recognition()
self.timer_camera = QtCore.QTimer()
self.cap = None
self.CAM_NUM = 0
self.set_ui()
self.slot_init()
self.__flag_work = 0
self.x = 0
self.count = 0
def set_ui(self):
self.__layout_main = QtWidgets.QHBoxLayout()
self.__layout_fun_button = QtWidgets.QVBoxLayout()
self.__layout_data_show = QtWidgets.QVBoxLayout()
self.button_open_camera = QtWidgets.QPushButton(u'开始播放')
self.button_pause = QtWidgets.QPushButton(u'暂停播放')
self.button_close = QtWidgets.QPushButton(u'关闭播放')
# Button 的颜色修改
button_color = [self.button_open_camera, self.button_pause, self.button_close]
for i in range(3):
button_color[i].setStyleSheet("QPushButton{color:black}"
"QPushButton:hover{color:red}"
"QPushButton{background-color:rgb(78,255,255)}"
"QPushButton{border:2px}"
"QPushButton{border-radius:10px}"
"QPushButton{padding:2px 4px}")
self.button_open_camera.setMinimumHeight(50)
self.button_pause.setMinimumHeight(50)
self.button_close.setMinimumHeight(50)
# move()方法移动窗口在屏幕上的位置到x = 300,y = 300坐标。
self.move(500, 500)
# 信息显示
self.label_show_camera = QtWidgets.QLabel()
self.label_move = QtWidgets.QLabel()
self.label_move.setFixedSize(100, 100)
self.label_show_camera.setFixedSize(641, 481)
self.label_show_camera.setAutoFillBackground(False)
self.__layout_fun_button.addWidget(self.button_open_camera)
self.__layout_fun_button.addWidget(self.button_pause)
self.__layout_fun_button.addWidget(self.button_close)
self.__layout_fun_button.addWidget(self.label_move)
self.__layout_main.addLayout(self.__layout_fun_button)
self.__layout_main.addWidget(self.label_show_camera)
self.setLayout(self.__layout_main)
self.label_move.raise_()
self.setWindowTitle(u'摄像头')
'''
# 设置背景图片
palette1 = QPalette()
palette1.setBrush(self.backgroundRole(), QBrush(QPixmap('background.png')))
self.setPalette(palette1)
'''
def slot_init(self):
self.button_open_camera.clicked.connect(self.button_open_camera_click)
self.button_pause.clicked.connect(self.button_pause_camera_click)
self.timer_camera.timeout.connect(self.show_camera)
self.button_close.clicked.connect(self.close)
def button_pause_camera_click(self):
self.timer_camera.blockSignals(False)
if self.timer_camera.isActive() == True and self.num % 2 == 1:
self.button_pause.setText(u'暂停播放')
self.num = self.num + 1
cv2.imwrite("screenshoot" + ".jpg", self.image)
self.timer_camera.blockSignals(True)
else:
self.num = self.num + 1
self.button_pause.setText(u'继续播放')
def button_open_camera_click(self):
if self.timer_camera.isActive() == False:
# flag = self.cap.open(self.CAM_NUM)
self.cap = cv2.VideoCapture("mda-hg6uempmez9u6mqi.mp4")
flag = self.cap.isOpened()
if flag == False:
msg = QtWidgets.QMessageBox.warning(self, u"Warning", u"请检测相机与电脑是否连接正确",
buttons=QtWidgets.QMessageBox.Ok,
defaultButton=QtWidgets.QMessageBox.Ok)
# if msg==QtGui.QMessageBox.Cancel:
# pass
else:
self.timer_camera.start(30)
self.button_open_camera.setText(u'关闭相机')
else:
self.timer_camera.stop()
self.cap.release()
self.label_show_camera.clear()
self.button_open_camera.setText(u'打开相机')
def show_camera(self):
flag, self.image = self.cap.read()
# face = self.face_detect.align(self.image)
# if face:
# pass
self.show = cv2.resize(self.image, (640, 480))
self.show = cv2.cvtColor(self.show, cv2.COLOR_BGR2RGB)
# print(show.shape[1], show.shape[0])
# show.shape[1] = 640, show.shape[0] = 480
showImage = QtGui.QImage(self.show.data, self.show.shape[1], self.show.shape[0], QtGui.QImage.Format_RGB888)
self.label_show_camera.setPixmap(
QtGui.QPixmap.fromImage(showImage)) # self.x += 1 # self.label_move.move(self.x,100)
# if self.x ==320: # self.label_show_camera.raise_()
def closeEvent(self, event):
ok = QtWidgets.QPushButton()
cacel = QtWidgets.QPushButton()
msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, u"关闭", u"是否关闭!")
msg.addButton(ok, QtWidgets.QMessageBox.ActionRole)
msg.addButton(cacel, QtWidgets.QMessageBox.RejectRole)
ok.setText(u'确定')
cacel.setText(u'取消')
# msg.setDetailedText('sdfsdff')
if msg.exec_() == QtWidgets.QMessageBox.RejectRole:
event.ignore()
else:
# self.socket_client.send_command(self.socket_client.current_user_command)
if self.timer_camera.isActive():
self.timer_camera.stop()
event.accept()
if __name__ == "__main__":
App = QApplication(sys.argv)
ex = Ui_MainWindow()
ex.show()
sys.exit(App.exec_())