1. 程式人生 > 其它 >Qt Designer設計介面三,Qlabel播放視訊檔案示例

Qt Designer設計介面三,Qlabel播放視訊檔案示例

功能:

1.播放,停止播放,迴圈播放一個視訊檔案

缺點:視窗大小固定不可調,因為一拉伸視窗就會導致程式停止執行,無解

 

效果圖:

 

 程式碼:

import sys
import cv2, time
from threading import Thread
from PySide2.QtGui import QImage, QPixmap
from PySide2.QtCore import Qt
from PySide2.QtWidgets import (QApplication, QMainWindow)
from p import Ui_MainWindow


class UI(QMainWindow, Ui_MainWindow):

    
def __init__(self): super(UI, self).__init__() self.setupUi(self) # 只保留視窗關閉按鈕, 禁止拉伸視窗大小 self.setWindowFlags(Qt.WindowCloseButtonHint) self.setFixedSize(self.width(), self.height()) self.b_close = False self.b_loop = False self.video_lbl.setStyleSheet(
"background-color: black") self.play_tool.triggered.connect(lambda : Thread(target=self.play_video).start()) self.stop_tool.triggered.connect(self.stop_video) self.loop_tool.triggered.connect(self.loop_video) def stop_video(self): if self.b_close == False: self.b_close
= True self.b_loop = True self.play_tool.setEnabled(True) def loop_video(self): if self.loop_tool.text() == '迴圈播放中': self.b_loop = False self.loop_tool.setText('當前為不迴圈播放') else: self.b_loop = True self.loop_tool.setText('迴圈播放中') def play_video(self): ''' 功能:播放影片 :return: ''' self.play_tool.setEnabled(False) self.b_close = False file = '1.mp4' self.cap = cv2.VideoCapture(file) if not self.cap.isOpened(): print('Cannot open video') return while not self.b_close: while True: # 此迴圈用於迴圈播放判斷 if self.b_close == True: break try: ret, frame = self.cap.read() if not ret: if frame is None: print('The video has end') self.video_lbl.clear() # 如果不迴圈播放就跳出 if self.b_loop == False: break else: self.cap.release() time.sleep(0.2) self.cap = cv2.VideoCapture(file) else: print('Read video error!') break width = self.video_lbl.size().width() height = self.video_lbl.size().height() frame = cv2.resize(frame, (width,height), interpolation=cv2.INTER_AREA) self.frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) self.qt_img = QImage(self.frame.data, self.frame.shape[1], self.frame.shape[0], self.frame.shape[1] * 3, QImage.Format_RGB888) self.video_lbl.setPixmap(QPixmap.fromImage(self.qt_img)) except: pass if self.b_loop == False: break self.cap.release() self.video_lbl.clear() self.play_tool.setEnabled(True) if __name__ == '__main__': app = QApplication([]) server = UI() server.show() sys.exit(app.exec_())