UOS python+Pyqt5实现显示接口测试

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'VideoTest.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


import sys
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QApplication, QWidget,QPushButton
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtCore import Qt
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5.QtCore import QUrl
from PyQt5.Qt import QTimer
import logging
import subprocess
from subprocess import Popen
import json
import configparser
import pyudev
import vlc
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QFrame
import random
#pip install pynput
from pynput import keyboard
from PyQt5.QtCore import QTimer, pyqtSignal
import os
os.environ['XDG_RUNTIME_DIR'] = '/tmp/runtime-' + os.environ['USER']
os.environ['VLC_PLUGIN_PATH'] = '/usr/lib/vlc/plugins'

class Ui_Form(QWidget):
    updateTimer = pyqtSignal(bool)  # 定义一个信号

    def __init__(self):
        super().__init__()
        self.config = configparser.ConfigParser()  #创建对象
        self.videoFileName=''#视频文件
        self.itemName=''#测试项目名称
        self.itemFailSleepExit=0#读取项目fail延时退出时间
        self.testArgs = []  # 测试参数信息
        self.testStandardArgs=''#标准参数
        self.testPorts=[]#测试接口集合
        self.random_number=0#随机数
        self.connected_displays=[]#连接显示端口信息
        #self.isInputckPass=False#输入的内容
        self.chkdisplay=False#核对接口状态
        self.currentPort=''#当前接口
        self.resolution = "1920x1080"  # 示例分辨率
        #self.actualTestinfo=[]#实际测试信息
        self.index=0#指针

        # 生成日志信息
        self.logger = logging.getLogger('my_logger')  # 步骤1 创建日志记录器
        self.logger.setLevel(logging.DEBUG)  # 步骤2 将指定日志级别
        self.file_handler = logging.FileHandler('./log/log.txt')  # 步骤3 创建文件处理器
        self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')  # 步骤4 创建格式化器
        self.file_handler.setFormatter(self.formatter)  # 步骤4 将格式化器添加到处理器
        self.logger.addHandler(self.file_handler)  # 步骤5 将处理器添加到日志记录器

        # 读取配置
        self.config.read('./Conf/config.conf', encoding='utf-8')  # 读取配置文件,如果配置文件不存在则创建

        #读取DiskPlay Port测试配置
        self.itemName=self.config.get('TestItemNameArrays','DisplayPortTestName')#测试项目名称
        self.videoFileName=self.config.get('TestItemCallFileName','DisplayPort')#视频播放文件
        self.itemFailSleepExit=int(self.config.get('TestItemWinFrmSleepExit','DisplayPortTestName'))#退出延时时间
        self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')  # 读取测试参数信息

        # 读取标准值
        if self.ReadJsonTestArgs(self.itemName) == True:
            self.testPorts=self.testStandardArgs.split('|')#读取测试参数

        self.setupUi()
        #遍历设置测试项目名
        for tspt in self.testPorts:
            if tspt=='VGA':
                self.label_5.setText('VGA')#VGA
                self.lbl_setVGA.setText('N/A')
            elif tspt=='DVI':
                self.label_4.setText('DVI')#DVI
                self.lbl_setDVI.setText('N/A')
            elif tspt=='HDMI':
                self.label_7.setText('HDMI')#HDMI
                self.lbl_setHDMI.setText('N/A')
            elif tspt == 'DP':
                self.label_6.setText('DP')  #DP
                self.lbl_setDP.setText('N/A')
        self.pb_Input_Num.setText('N/A')#随机数产线栏

        #视频解码
        self.instance = vlc.Instance()
        self.player = self.instance.media_player_new()
        self.events = self.player.event_manager()
        self.events.event_attach(vlc.EventType.MediaPlayerEndReached, self.media_end_reached)

        # 将video_widget添加到布局
        self.videoframe = QFrame(self)
        self.lay_Play.addWidget(self.videoframe)
        self.play_video()

        # 设置键盘监听
        self.start_keyboard_listener()

        # 创建一个定时器来检查视频是否播放结束
        self.timer_1 = QTimer(self)
        self.timer_1.setInterval(1000)  # 每秒检查一次
        self.timer_1.timeout.connect(self.check_Test)
        self.timer_1.start()

        # 将信号连接到定时器的启动和停止槽
        #self.start_signal.connect(self.timer_1.start)#启动
        #self.stop_signal.connect(self.timer_1.stop)#停用
        # 连接信号到槽
        self.updateTimer.connect(self.handleTimer)

    #定义触发器
    def handleTimer(self, start):
        if start:
            self.timer_1.start()
        else:
            self.timer_1.stop()

    #核对测试
    def check_Test(self):
        try:
            if self.index>=len(self.testPorts):#判断是否PASS
                sys.exit(0)
            else:
                print(str(self.index),self.testPorts)
                #self.stopTimer()#时针控件暂停执行
                self.updateTimer.emit(False)  # 发射信号以停止定时器
                #先清空所有背景色
                self.label_5.setStyleSheet("")  # VGA设置背景颜色为空
                self.label_4.setStyleSheet("")  # DVI设置背景颜色为空
                self.label_7.setStyleSheet("")  # HDMI设置背景颜色为空
                self.label_6.setStyleSheet("")  # DP设置背景颜色为空
                self.pb_Input_Num.setText('')  # 随机数为空
                self.lbl_Input_hint.setText('')#提示信息
                self.pb_Input_Num.setEnabled(False)
                if self.testPorts[self.index]=='VGA':
                    self.label_5.setStyleSheet("background-color: lightgreen;")  # 设置背景浅绿色
                elif self.testPorts[self.index]=='DVI':
                    self.label_4.setStyleSheet("background-color: lightgreen;")  # 设置背景浅绿色
                elif self.testPorts[self.index]=='HDMI':
                    self.label_7.setStyleSheet("background-color: lightgreen;")  # 设置背景浅绿色
                elif self.testPorts[self.index]=='DP':
                    self.label_6.setStyleSheet("background-color: lightgreen;")  # 设置背景浅绿色
                self.label_8.setText(self.testPorts[self.index] + '接口测试')
                self.lbl_Result.setText(self.testPorts[self.index] + '接口检测中..')
                self.lbl_Result.setStyleSheet('color:yellow;')
                if self.JudgmentInclusion(self.testPorts[self.index])==True:
                    self.set_display(self.currentPort,self.resolution)#强制切换显示
                    self.random_number = random.randint(1, 9)  # 生成一到9的随机数
                    self.pb_Input_Num.setText(str(self.random_number))  # 随机数
                    self.lbl_Input_hint.setText('请输入键盘上的数字键:' + str(self.random_number))
                    self.chkdisplay = True
                else:
                    self.lbl_Result.setText('检测'+self.testPorts[self.index]+'信号失败,请确认'+self.testPorts[self.index]+'是否连接正常!!')
                    self.lbl_Result.setStyleSheet('color:red;')
                    if self.testPorts[self.index]=='VGA':
                        self.lbl_setVGA.setText('FAIL')
                        self.lbl_setVGA.setStyleSheet('color:red;')
                    elif self.testPorts[self.index]=='DVI':
                        self.lbl_setDVI.setStyleSheet('color:red;')
                        self.lbl_setDVI.setText('FAIL')
                    elif self.testPorts[self.index]=='HDMI':
                        self.lbl_setHDMI.setText('FAIL')
                        self.lbl_setHDMI.setStyleSheet('color:red;')
                    elif self.testPorts[self.index]=='DP':
                        self.lbl_setDP.setText('FAIL')
                        self.lbl_setDP.setStyleSheet('color:red;')
                    #self.startTimer()#启用时钟
                    self.updateTimer.emit(True)  # 发射信号启动定时器
        except subprocess.CalledProcessError as e:
            self.ShowLog("check_Test:" + str(e), False)
            print(f"check_Test: {e}")
            self.mirror_displays()  # 复制屏显示
            sys.exit(1)

    #判断集合字典中是否包含该字符串内容 arrayDictionary:集合字典,str字符串
    def JudgmentInclusion(self,str):
        try:
            if self.get_connected_displays() == True:
                for cndkps in self.connected_displays:
                    print(cndkps)
                    self.currentPort=cndkps['name']
                    print(self.currentPort)
                    if str=='HDMI':
                        if 'HDMI' in cndkps['name'] or 'DisplayPort-0' in cndkps['name'] or 'DigitalOutput-0' in cndkps['name']:
                            return True
                    elif str=='DP':
                        if 'DP' in cndkps['name'] or 'DisplayPort-1' in cndkps['name'] or 'DigitalOutput-1' in cndkps['name']:
                            return True
                    else:
                        if str in cndkps['name']:
                            print('PASS',self.currentPort)
                            return True
                return False
            else:
                self.lbl_Result.setText('检测'+self.currentPort+'信号失败,请确认'+self.currentPort+'是否连接正常!!')
                self.lbl_Result.setStyleSheet('color:red;')
                #self.timer_1.start()  # 重新启动时针
                return False
        except subprocess.CalledProcessError as e:
            self.ShowLog("Error setting display:" + str(e), False)
            print(f"Error setting display: {e}")
            sys.exit(1)

    #复制屏显示
    def mirror_displays(self):
        try:
            #cmd = ''
            if self.get_connected_displays() == True:
                if len(self.connected_displays) > 1:
                    #cmd=f'xrandr --output {self.connected_displays[0]["name"]}  --auto --output --mode {resolution} --output {self.connected_displays[1]["name"]} --auto --same -as {self.connected_displays[0]["name"]}'
                    # 设置主显示器的分辨率
                    subprocess.run(f"xrandr --output {self.connected_displays[0]['name']} --mode {self.resolution} --primary", shell=True,
                                   check=True)
                    # 设置辅助显示器以复制主显示器
                    subprocess.run(f"xrandr --output {self.connected_displays[1]['name']} --mode {self.resolution} --same-as {self.connected_displays[0]['name']}",
                                   shell=True, check=True)
                    print(f"Mirrored displays: {self.connected_displays[0]['name']} and {self.connected_displays[1]['name']} to resolution {self.resolution}")

            '''xrandr - -output
            HDMI - 1 - -auto - -output
            eDP - 1 - -auto - -same - as HDMI - 1'''

        except subprocess.CalledProcessError as e:
            self.ShowLog("Error mirroring displays:" + str(e), False)
            print(f"Error mirroring displays: {e}")

    #强制切换显示接口显示
    def set_display(self,output, resolution):
        try:
            # 构建xrandr命令

            #self.testPorts[self.index]
            cmd=''
            i=0
            if self.get_connected_displays() == True:
                for cd_display in self.connected_displays:
                    print('cd_display',cd_display)
                    if output == 'HDMI':
                        if 'HDMI' in cd_display['name'] or 'DisplayPort-0' in cd_display['name'] or 'DigitalOutput-0' in cd_display['name']:
                            break
                    elif output == 'DP':
                        if 'DP' in cd_display['name'] or 'DisplayPort-1' in cd_display['name'] or 'DigitalOutput-1' in cd_display['name']:
                            break
                    else:
                        if output in cd_display['name']:
                            break
                    i+=1

                if len(self.connected_displays)>1:
                    if i>=1:
                        cmd=f'xrandr --output {self.connected_displays[i]["name"]} --auto --mode {resolution} --output {self.connected_displays[i-1]["name"]} --off'
                    else:
                        cmd = f'xrandr --output {self.connected_displays[i]["name"]} --auto --mode {resolution} --output {self.connected_displays[i + 1]["name"]} --off'
                    #cmd = f"xrandr --output {output} --mode {resolution}"
                    subprocess.run(cmd, shell=True, check=True)
                    print(f"Display {output} set to resolution {resolution}")
        except subprocess.CalledProcessError as e:
            self.ShowLog("Error setting display:" + str(e), False)
            print(f"Error setting display: {e}")
            sys.exit(1)

    #检查当前显示器接入的信号源
    def get_connected_displays(self):
        try:
            # 运行xrandr命令
            output = subprocess.check_output("xrandr", stderr=subprocess.STDOUT)
            lines = output.decode('utf-8').split('\n')
            self.connected_displays.clear()#清空接口信息
            # 解析xrandr的输出
            for line in lines:
                if ' connected ' in line:
                    # 分割字符串以获取显示器名称和状态
                    parts = line.split()
                    display = {
                        "name": parts[0],
                        "status": "connected" if "connected" in parts else "disconnected",
                        "resolution": parts[2] if len(parts) > 2 else "unknown"
                    }
                    self.connected_displays.append(display)
            if len(self.connected_displays)>0:
                return True
            else:
                return False

        except subprocess.CalledProcessError as e:
            print("Error: ", e.output)
            self.ShowLog("get_connected_displays Error:" + e.output, False)
            sys.exit(1)

    #增加线程
    def start_keyboard_listener(self):
        listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)
        listener.start()

    #键盘按下
    def on_press(self,key):
        try:
            print(f"Alphanumeric key pressed: {key.char}")
            print(str(int(self.random_number)),str(int(key.char)),self.chkdisplay)
            if int(self.random_number)==int(key.char) and self.chkdisplay == True:
                self.lbl_Result.setText('检测' + self.testPorts[self.index] + '测试通过!!')
                self.lbl_Result.setStyleSheet('color:green;')
                if self.testPorts[self.index]=='VGA':
                    self.lbl_setVGA.setText('PASS')
                    self.lbl_setVGA.setStyleSheet('color:green;')
                    self.chkdisplay = False
                    self.index += 1
                elif self.testPorts[self.index]=='DVI':
                    self.lbl_setDVI.setStyleSheet('color:green;')
                    self.lbl_setDVI.setText('PASS')
                    self.chkdisplay = False
                    self.index += 1
                elif self.testPorts[self.index]=='HDMI':
                    self.lbl_setHDMI.setText('PASS')
                    self.lbl_setHDMI.setStyleSheet('color:green;')
                    self.chkdisplay = False
                    self.index += 1
                elif self.testPorts[self.index]=='DP':
                    self.lbl_setDP.setText('PASS')
                    self.lbl_setDP.setStyleSheet('color:green;')
                    self.chkdisplay = False
                    self.index += 1
                #self.timer_1.start()  # 启动时钟
                #self.updateTimer.emit(True)  # 发射信号以启动定时器
                self.updateTimer.emit(True)  # 发射信号以启动定时器
                self.mirror_displays()#复制屏显示
            #self.inputNum=str(key.char)
        except AttributeError:
            print(f"Special key pressed: {key}")
            self.ShowLog(f"Special key pressed: {key}", False)
            self.mirror_displays()  # 复制屏显示
            sys.exit(1)

    #键盘松开
    def on_release(self,key):
        print(f"Key released: {key}")
        if key == keyboard.Key.esc:
            # 停止监听
            return False

    #检查当前显示接口
    #port:端口号
    def DetectionDiskplayPort(self,port):
        try:
            return True
        except Exception as e:
            self.ShowLog("Test "+port+" Err:" + str(e),False)
            sys.exit(1)

    def get_display_interfaces(self):
        context = pyudev.Context()
        display_interfaces = []

        for device in context.list_devices(subsystem='video4linux'):
            if 'ID_INPUT' in device and 'HDMI' in device['ID_INPUT']:
                display_interfaces.append('HDMI')
            elif 'ID_INPUT' in device and 'VGA' in device['ID_INPUT']:
                display_interfaces.append('VGA')
            elif 'ID_INPUT' in device and 'DVI' in device['ID_INPUT']:
                display_interfaces.append('DVI')
            elif 'ID_INPUT' in device and 'DP' in device['ID_INPUT']:
                display_interfaces.append('DP')

        return display_interfaces

    def setupUi(self):
        self.setObjectName("Display Port Test")
        self.resize(1108, 734)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("IMAGE/DisPlay.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.gridLayout = QtWidgets.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.verticalLayout_6 = QtWidgets.QVBoxLayout()
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        self.lbl_logo = QtWidgets.QLabel(self)
        self.lbl_logo.setText("")
        self.lbl_logo.setPixmap(QtGui.QPixmap("IMAGE/logo.jpg"))
        self.lbl_logo.setObjectName("lbl_logo")
        self.verticalLayout_6.addWidget(self.lbl_logo)
        self.horizontalLayout_4.addLayout(self.verticalLayout_6)
        self.verticalLayout_9 = QtWidgets.QVBoxLayout()
        self.verticalLayout_9.setObjectName("verticalLayout_9")
        self.lbl_Title = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(16)
        font.setBold(False)
        font.setWeight(50)
        self.lbl_Title.setFont(font)
        self.lbl_Title.setStyleSheet("background-color: rgb(170, 170, 127);")
        self.lbl_Title.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Title.setObjectName("lbl_Title")
        self.verticalLayout_9.addWidget(self.lbl_Title)
        self.label_8 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(13)
        self.label_8.setFont(font)
        self.label_8.setStyleSheet("background-color: rgb(170, 255, 127);")
        self.label_8.setAlignment(QtCore.Qt.AlignCenter)
        self.label_8.setObjectName("label_8")
        self.verticalLayout_9.addWidget(self.label_8)
        self.horizontalLayout_4.addLayout(self.verticalLayout_9)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label.setObjectName("label")
        self.verticalLayout_4.addWidget(self.label)
        self.label_3 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.label_3.setFont(font)
        self.label_3.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_3.setObjectName("label_3")
        self.verticalLayout_4.addWidget(self.label_3)
        self.horizontalLayout_4.addLayout(self.verticalLayout_4)
        self.verticalLayout_5 = QtWidgets.QVBoxLayout()
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.label_5 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_5.setFont(font)
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_8.addWidget(self.label_5)
        self.label_4 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_8.addWidget(self.label_4)
        self.verticalLayout_5.addLayout(self.horizontalLayout_8)
        self.horizontalLayout_10 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_10.setObjectName("horizontalLayout_10")
        self.lbl_setVGA = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.lbl_setVGA.setFont(font)
        self.lbl_setVGA.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_setVGA.setObjectName("lbl_setVGA")
        self.horizontalLayout_10.addWidget(self.lbl_setVGA)
        self.lbl_setDVI = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.lbl_setDVI.setFont(font)
        self.lbl_setDVI.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_setDVI.setObjectName("lbl_setDVI")
        self.horizontalLayout_10.addWidget(self.lbl_setDVI)
        self.verticalLayout_5.addLayout(self.horizontalLayout_10)
        self.horizontalLayout_4.addLayout(self.verticalLayout_5)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_7 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_7.setFont(font)
        self.label_7.setAlignment(QtCore.Qt.AlignCenter)
        self.label_7.setObjectName("label_7")
        self.horizontalLayout_3.addWidget(self.label_7)
        self.label_6 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_6.setFont(font)
        self.label_6.setAlignment(QtCore.Qt.AlignCenter)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_3.addWidget(self.label_6)
        self.verticalLayout_3.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.lbl_setHDMI = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.lbl_setHDMI.setFont(font)
        self.lbl_setHDMI.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_setHDMI.setObjectName("lbl_setHDMI")
        self.horizontalLayout_7.addWidget(self.lbl_setHDMI)
        self.lbl_setDP = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.lbl_setDP.setFont(font)
        self.lbl_setDP.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_setDP.setObjectName("lbl_setDP")
        self.horizontalLayout_7.addWidget(self.lbl_setDP)
        self.verticalLayout_3.addLayout(self.horizontalLayout_7)
        self.horizontalLayout_4.addLayout(self.verticalLayout_3)
        self.horizontalLayout.addLayout(self.horizontalLayout_4)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.lay_Play = QtWidgets.QVBoxLayout()
        self.lay_Play.setObjectName("lay_Play")
        self.verticalLayout.addLayout(self.lay_Play)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.verticalLayout_7 = QtWidgets.QVBoxLayout()
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        self.lbl_Input_hint = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.lbl_Input_hint.setFont(font)
        self.lbl_Input_hint.setStyleSheet("background-color: rgb(255, 255, 127);")
        self.lbl_Input_hint.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Input_hint.setWordWrap(True)
        self.lbl_Input_hint.setObjectName("lbl_Input_hint")
        self.verticalLayout_7.addWidget(self.lbl_Input_hint)
        self.horizontalLayout_2.addLayout(self.verticalLayout_7)
        self.verticalLayout_8 = QtWidgets.QVBoxLayout()
        self.verticalLayout_8.setObjectName("verticalLayout_8")
        self.pb_Input_Num = QtWidgets.QPushButton(self)
        font = QtGui.QFont()
        font.setPointSize(20)
        self.pb_Input_Num.setFont(font)
        self.pb_Input_Num.setObjectName("pb_Input_Num")
        self.verticalLayout_8.addWidget(self.pb_Input_Num)
        self.horizontalLayout_2.addLayout(self.verticalLayout_8)
        self.video_Information = QtWidgets.QVBoxLayout()
        self.video_Information.setObjectName("video_Information")
        self.lbl_Result = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(19)
        self.lbl_Result.setFont(font)
        self.lbl_Result.setStyleSheet("background-color: rgb(0, 0, 0);\n"
                                      "color: rgb(255, 255, 127);")
        self.lbl_Result.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Result.setObjectName("lbl_Result")
        self.video_Information.addWidget(self.lbl_Result)
        self.horizontalLayout_2.addLayout(self.video_Information)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)0#
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)  # 只显示最小化按钮和关闭按钮

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("VideoTest", "Display Port Test"))
        self.lbl_Title.setText(_translate("VideoTest", "Display Port Test"))
        self.label_8.setText(_translate("VideoTest", "当前VGA测试中.."))
        self.label.setText(_translate("VideoTest", "测试接口:"))
        self.label_3.setText(_translate("VideoTest", "测试结果:"))
        self.label_5.setText(_translate("VideoTest", ""))
        self.label_4.setText(_translate("VideoTest", ""))
        self.lbl_setVGA.setText(_translate("VideoTest", ""))
        self.lbl_setDVI.setText(_translate("VideoTest", ""))
        self.label_7.setText(_translate("VideoTest", ""))
        self.label_6.setText(_translate("VideoTest", ""))
        self.lbl_setHDMI.setText(_translate("VideoTest", ""))
        self.lbl_setDP.setText(_translate("VideoTest", ""))
        self.lbl_Input_hint.setText(_translate("VideoTest", "请根据提醒数字,按键盘输入对应数字"))
        self.pb_Input_Num.setText(_translate("VideoTest", "5"))
        self.lbl_Result.setText(_translate("VideoTest", "Wait"))

    #读取json信息
    def ReadJsonInfo(self,fileName):
        try:
            if os.path.exists(fileName):
                f=open(fileName,'r',encoding='utf-8')
            return json.loads(f.read())
        except Exception as e:
            self.ShowLog("Read "+fileName+" Err:" + str(e),False)
            sys.exit(1)

    #读取项目参数信息,itemName:项目名称
    def ReadJsonTestArgs(self,itemName):
        try:
            self.testArgs=self.ReadJsonInfo('./Conf/TestArgs.json')
            for js in self.testArgs:
                if itemName in js['ItemName']:
                    self.testStandardArgs=js['Standard']
                    return True
            self.ShowLog('Read TestArgs.json ItemName:'+itemName+' Info Is Empty!!',False)
            sys.exit(1)
        except Exception as e:
            self.ShowLog("Read TestArgs.json ItemName:"+itemName+" Info Err:" + str(e),False)
            sys.exit(1)

    #播放视频
    #def play_video(self):
    #    if self.media_player.state() == QMediaPlayer.PlayingState:
    #        self.media_player.pause()
    #    else:
    #        self.media_player.play()
            #loop = self.media_content.isLoopback()  # 获取当前是否循环播放的状态
            #loop = self.media_player.playbackMode() == QMediaPlayer.LoopingMedia  # 获取当前是否循环播放的状态
            #loop = self.media_player.repeatMode() == QMediaPlayer.RepeatOne  # 获取当前是否循环播放的状态
            #self.media_player.setPlaybackMode(QMediaPlayer.Looping)  # 设置循环播放模式
            # 如果当前不是循环播放,则在视频播放结束后重新开始播放
            #if not loop:
            #    self.media_player.positionChanged.connect(self.check_position)
            #    self.check_position(0)

    #def check_position(self, position):
    #    duration = self.media_content.duration() / 1000  # 获取视频时长(秒)
    #    if position >= duration:  # 如果已经播放到视频末尾,则重新开始播放
    #        self.media_player.setPosition(0)
    #        self.media_player.positionChanged.disconnect(self.check_position)  # 断开信号连接,避免重复触发问题
    #    else:
    #        return True

    #播放音频
    def play_video(self):
        # 注意:在这里替换为你的视频文件路径
        media = self.instance.media_new(self.videoFileName)#self.videoFileName读取音频文件
        self.player.set_media(media)

        # 在 Windows 上,设置播放器的绘制窗口
        if sys.platform.startswith('win'):
            self.player.set_hwnd(self.videoframe.winId())
        elif sys.platform.startswith('linux'):  # 在 Linux 上
            self.player.set_xwindow(self.videoframe.winId())
        # MacOS 的实现可能不同

        # 绑定播放结束事件
        #self.events.event_attach(vlc.EventType.MediaPlayerEndReached, self.media_end_reached)

        self.player.play()

        # 创建一个定时器来检查视频是否播放结束
        self.timer = QTimer(self)
        self.timer.setInterval(1000)  # 每秒检查一次
        self.timer.timeout.connect(self.check_end)
        self.timer.start()

    def check_end(self):
        # 如果视频播放结束,则重新开始播放
        if self.player.get_state() == vlc.State.Ended:
            self.player.stop()
            self.player.play()

    def media_end_reached(self, event):
        # 当视频播放结束时,重置播放位置到开始,并继续播放
        self.player.set_position(0)
        self.player.play()

    # 定义一个函数使得函数窗口居中显示
    def Center(self):
        # 获取屏幕尺寸
        screen_geometry = app.desktop().availableGeometry()
        # 计算窗口居中位置
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        # 设置窗口位置
        self.move(x, y)

    #打印的信息
    def ShowLog(self,log,isPass):
        try:
            if isPass == True:
                self.logger.info(str(log))
            else:
                print("\033[1;31m" + str(str(log)) + " \033[0m")
                self.logger.error(str(log))
        except Exception as e:
            print("\033[1;31m" + str(e) + " \033[0m")
            sys.exit(1)

    #窗口关闭
    def closeEvent(self, event):
        # 创建一个消息框,上面有两个按钮:“是”和“否”
        #reply = QMessageBox.question(self, '退出', "你确定要退出吗?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        # 如果用户点击了“是”,则执行event.accept()来关闭窗口
        #if reply == QMessageBox.Yes:
        #    event.accept()
        #    sys.exit(1)
        #else:
            # 如果用户点击了“否”,则忽略event,不关闭窗口
        #    event.ignore()
        self.mirror_displays()  # 复制屏显示
        sys.exit(1)

    #禁止设整窗体大小
    def resizeEvent(self, event):
        # 获取当前窗口的大小
        current_size = self.size()

        # 设置窗口的最大大小和最小大小,使其无法通过鼠标调整
        self.setMaximumSize(current_size)
        self.setMinimumSize(current_size)

        # 调用父类的resizeEvent方法,以便正常调整窗口大小
        super().resizeEvent(event)

if __name__=='__main__':
    app=QApplication(sys.argv)
    win=Ui_Form()
    win.Center()  # 居中
    win.show()
    sys.exit(app.exec_())

'''
 # 主显示器名称和辅助显示器名称
    primary_output = "eDP-1"  # 通常是内置显示器,如笔记本屏幕
    secondary_output = "HDMI-1"  # 例如,外接HDMI显示器
    resolution = "1920x1080"  # 设置两个显示器的分辨率

    mirror_displays(primary_output, secondary_output, resolution)
'''
'''
    # 要设置的显示器名称和分辨率
    output_name = "HDMI-1"  # 示例:HDMI-1, VGA-1, DP-1 等
    resolution = "1920x1080"  # 示例分辨率

    set_display(output_name, resolution)
'''
'''
 displays = get_connected_displays()
    for display in displays:
        print(f"Display: {display['name']}, Status: {display['status']}, Resolution: {display['resolution']}")
'''

展示UIUOS python+Pyqt5实现显示接口测试_第1张图片

你可能感兴趣的:(python,qt,开发语言)