UOS python+pyqt5实现USB测试

发布时间:2023年12月29日
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'UsbTest.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# 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 QApplication, QWidget, QGridLayout
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5.Qt import QTimer
import logging
import subprocess
from subprocess import Popen
import os
import json
import configparser
#import pyudev #pip install pyudev USB接入后自动触发事件
#import time

class Ui_UsbTestMainFrm(QWidget):
    def __init__(self):
        super().__init__()
        self.config = configparser.ConfigParser()  # 创建对象
        self.Usb_info = []  # Usb信息
        self.StorageName = []  # 所有存储器名称
        self.testArgs = []  # 测试参数信息
        self.testStandardArgs = ''  # 测试标准参数
        self.itemName = ''  # 项目名称
        self.itemFailSleepExit = 0  # 项目Fail延时退出
        self.testUsb2Count=0#测试USB2.0数量
        self.testUsb2Device=[]#usb2.0硬件信息
        self.testUsb3Count=0#测试USB3.0数量
        self.testUsb3Device=[]#usb3.0硬件信息
        self.readUsb2Count=0#读取USB2.0数量
        self.readUsb3Count=0#读取USB3.0数量
        self.PassUsbInfo=[]#测试PASS数据
        #self.readUsb2DeviceId=''#读取的Usb2硬件信息
        #self.readUsb3DeviceId=''#读取的Usb3硬件信息
        self.readUsbDeviceIds=''#读取usb装置集
        self.addUiDeviceIds=''#已添加到Ui的数据
        self.isStartTime=False
        self.index=0
        self.usb_layout= QHBoxLayout()

        # 生成日志信息
        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')  # 读取配置文件,如果配置文件不存在则创建

        # 读取测试配置
        self.itemName=self.config.get('TestItemNameArrays','UsbTestName')#项目测试Fail延时退出
        self.itemFailSleepExit=int(self.config.get('TestItemWinFrmSleepExit','UsbTest'))#项目测试Fail延时退出
        self.testArgs=self.ReadJsonInfo('./Conf/TestArgs.json')#读取测试参数信息

        #读取标准值
        if self.ReadJsonTestArgs(self.itemName)==True:
            testArgs=[]#测试参数
            usb2Args=[]#usb2.0测试参数
            usb3Args=[]#usb3.0测试参数
            testArgs=self.testStandardArgs.split('|')
            usb2Args=testArgs[0]#分割usb2.0测试参数
            usb3Args=testArgs[1]#分割usb3.0测试参数

            #读取USB2.0数量
            self.testUsb2Count =int(usb2Args[usb2Args.find('=') + 1:])
            #读取USB3.0数量
            self.testUsb3Count =int(usb3Args[usb3Args.find('=') + 1:])

            self.setupUi()

            #设置配置数量
            self.lbl_setUsb3Num.setText(str(self.testUsb3Count))#设置USB3.0数量
            self.lbl_setUsb2Num.setText(str(self.testUsb2Count))#设置USB2.0数量

            #程式启动自动测试
            if self.UsbPortTest() == True:
                # 同步当前时间
                # 创建一个定时器,用于更新QLCDNumber的时间
                sys.exit(0)
            self.timer = QTimer()
            self.timer.timeout.connect(self.update_time)
            self.timer.start(1000)  # 每隔1000毫秒(1秒)更新一次时间


            #usb接入触发事件
            #context = pyudev.Context()
            #monitor = pyudev.Monitor.from_netlink(context)
            #monitor.filter_by(subsystem='usb')
            #observer = pyudev.MonitorObserver(monitor, callback=self.usb_event_handler)
            #observer.start()

    #Ui刷新
    #def paintEvent(self, event):
    #    super().paintEvent(event)
    #    if self.index>=5:
     #       self.resize(737, 653)
    #    print("界面已刷新")

    #usb接入触发事件
    #def usb_event_handler(self,device):
    #    print("USB设备已接入:", device)
    #    if self.UsbPortTest() == True:
            # 同步当前时间
            # 创建一个定时器,用于更新QLCDNumber的时间
    #        self.timer = QTimer()
    #        self.timer.timeout.connect(self.update_time)
    #        self.timer.start(1000)  # 每隔1000毫秒(1秒)更新一次时间
    def toggleResize(self):
        self.resize(737, 853)

    #Usb接口测试
    def UsbPortTest(self):
        try:
            #self.Usb_info.clear()#清空Usb装置信息
            if self.GetDirectoryAllFileName('/sys/block'):
                for deviceName in self.StorageName:
                    self.ReadStorageInfo('/dev/' + deviceName)
                readUsbDeviceId=''
                for usbinfo in self.Usb_info:#遍历USB读取
                    isPass=False
                    usbDeviceIds = usbinfo['DeviceId'].split('/')
                    # deviceId:硬件ID,portType:端口类型,读取的硬件地址,rBrand:读取的品牌规格,rSize:容量大小,rType:读取类型
                    if usbDeviceIds[1] not in self.readUsbDeviceIds:
                        self.readUsbDeviceIds+=usbDeviceIds[1]+','
                        if usbinfo['Type']=='usb2' or usbinfo['Type']=='usb1':
                            self.readUsb2Count+=1
                            self.PassUsbInfo.append(usbinfo)
                        elif usbinfo['Type']=='usb3':
                            self.readUsb3Count+=1
                            self.PassUsbInfo.append(usbinfo)
                self.lbl_readUsb3Num.setText(str(self.readUsb3Count))  # 读取3.0数量
                self.lbl_readUsb2Num_2.setText(str(self.readUsb2Count))  # 读取2.0数量

                for psUsbInfo in self.PassUsbInfo:
                    #readUsbDeviceId+=psUsbInfo['DeviceId']+','
                    readDeviceIds =[]
                    readDeviceIds=psUsbInfo['DeviceId'].split('/')
                    if self.index==0 or readDeviceIds[1] not in self.addUiDeviceIds:
                        self.addUiDeviceIds+=readDeviceIds[1]+','
                        # deviceId:硬件ID,portType:端口类型,读取的硬件地址,rBrand:读取的品牌规格,rSize:容量大小,rType:读取类型
                        # def __init__(self, deviceId, portType, rdevicePath, rBrand, rSize, rType):
                        usbTest = Ui_Form(psUsbInfo['DevicePath'], psUsbInfo['Type'] + '.0', psUsbInfo['DevicePath'],psUsbInfo['Brand'], psUsbInfo['Size'], readDeviceIds[1])
                        if (self.index) % 2 == 0:  # 创建新的水平布局
                            self.usb_layout = QHBoxLayout()
                            self.layout_teui.addLayout(self.usb_layout)
                        self.usb_layout.addWidget(usbTest)  # 添加最后一个水平布
                        self.index+=1
                        
                        #usb_layout.addWidget(usbTest)#
                        #self.layout_teui.addLayout(usb_layout)
                readValue='usb2='+str(self.readUsb2Count)+'|'+'usb3='+str(self.readUsb3Count)
                if self.testUsb2Count==self.readUsb2Count and self.testUsb3Count==self.readUsb3Count:
                    self.lbl_log.setStyleSheet("color:green;")
                    self.lbl_log.setText('PASS')
                    self.UpdateJsonTestArgs(self.itemName, readValue, 'PASS')
                    return True
                else:
                    self.lbl_log.setText('测试中...')
                    self.UpdateJsonTestArgs(self.itemName, readValue, 'FAIL')
                    self.isStartTime=True
                    return False
            else:
                self.ShowLog("Get Usb Device Name Is Empty!!", False)
                sys.exit(1)
        except Exception as e:
            self.ShowLog("Usb Port Test Err:" + str(e),False)
            sys.exit(1)

    #获取目录下所有文件名
    def GetDirectoryAllFileName(self,DirectoryName):
        try:
            self.StorageName.clear()#清空存储器信息
            # 获取指定目录下所有文件名
            file_names = os.listdir(DirectoryName)

            # 遍历读取所有文件名称
            for file_name in file_names:
                self.StorageName.append(file_name)

            if len(self.StorageName)>0:
                return True
            else:
                return False
        except Exception as e:
            self.ShowLog("Read "+DirectoryName+" Directory Info Err:" + str(e),False)
            sys.exit(1)

    #同步当前时间
    def update_time(self):
        # 获取当前时间
        #current_time = QTime.currentTime()
        if self.isStartTime==True:
            self.isStartTime=False
            #if self.index>=5:
            #    self.toggleResize()
            if self.UsbPortTest()==True:
                sys.exit(0)


        #current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 将当前时间显示在QLCDNumber上

    #读取项目参数信息,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)

    #更新测试参数json,itemName:项目名称,readValue:读取值,testResult:测试结果
    def UpdateJsonTestArgs(self,itemName,readValue,testResult):
        try:
            updateTestArgs=[]#更新的测试参数
            self.testArgs=self.ReadJsonInfo('./Conf/TestArgs.json')
            for js in self.testArgs:
                if itemName in js['ItemName']:
                    js['Read']=readValue#读取的值
                    js['TestResult']=testResult#测试结果
                    updateTestArgs.append(js)
                else:
                    updateTestArgs.append(js)
            with open("./Conf/TestArgs.json", "w") as write_file:
                json.dump(updateTestArgs, write_file)
            return True
        except Exception as e:
            self.ShowLog("Read TestArgs.json ItemName:"+itemName+" Info Err:" + str(e),False)
            sys.exit(1)

    #读取存储器设备信息
    def ReadStorageInfo(self,devicePath):
        try:
            #devicePath:设备路径名称、Size:存信器大小、Type:储寄器类存、Barand:品牌规格、ID_SERIAL:设备通讯信息、DevLinks:设备连接信息
            tempStorageInfo={'DevicePath':'N/A','Size':'N/A','Type':'N/A','Brand':'N/A','DeviceId':'N/A','reads':'N/A',
            'Serial_Number':'N/A','FW':'N/A','Power_Cycles':'N/A','Power_On_Hours':'N/A','Temperature':'N/A'}#临时的存储器信息
            tempStorageInfo['DevicePath']=devicePath#设备路径名称
            ID_SERIAL=self.RuncmdGetInfo('udevadm info --query=property --name='+devicePath+' | grep "ID_SERIAL="')
            DEVLINKS =self.RuncmdGetInfo('udevadm info --query=property --name=' + devicePath + ' | grep "DEVLINKS="')
            ID_BUS =self.RuncmdGetInfo('udevadm info --query=property --name=' + devicePath + ' | grep "ID_BUS="')
            DEVPATH=self.RuncmdGetInfo('udevadm info --query=property --name=' + devicePath + ' | grep "DEVPATH="')
            DiskSize=self.RuncmdGetInfo("fdisk -l | grep 'Disk '"+devicePath)
            DiskSize=DiskSize[DiskSize.find(':')+2:DiskSize.find(',')]
            ID_PART_TABLE_TYPE = self.RuncmdGetInfo('udevadm info --query=property --name=' + devicePath + ' | grep "ID_PART_TABLE_TYPE="')
            tempStorageInfo['Brand']=ID_SERIAL[ID_SERIAL.find('=')+1:]
            tempStorageInfo['Brand']=tempStorageInfo['Brand'][:tempStorageInfo['Brand'].find('_')]#厂商
            tempStorageInfo['Size']=DiskSize#存储器大小
            #tempStorageInfo['DevLinks']=DEVLINKS[DEVLINKS.find('=')+1:]
            if len(ID_BUS)>0:
                #reads = self.RuncmdGetInfo('hdparm -tT ' + devicePath + ' | grep "Timing buffered disk reads"')
                #reads = reads[reads.find('=') + 2:]
                #tempStorageInfo['reads'] = reads  # 读写的速率
                temp=DEVPATH[DEVPATH.find('/usb')+1:DEVPATH.find('/host')]
                tempStorageInfo['Type']=temp[:temp.find('/')]#设备类型
                tempStorageInfo['DeviceId']=temp[len(tempStorageInfo['Type'])+1:]#硬件ID
                self.Usb_info.append(tempStorageInfo)
                return True
        except Exception as e:
            self.ShowLog("Read "+devicePath+" Device Info Err:" + str(e),False)
            sys.exit(1)

    #读取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)

    #执行命令行,并获取信息
    def RuncmdGetInfo(self,cmd):
        try:
            readcmdinfo=Popen([cmd],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            #获取子进程输出
            stdout,stderr=readcmdinfo.communicate()
            #将输出转换成字符串
            return stdout.decode("utf-8").strip()#返回数据
        except Exception as e:
            self.ShowLog("Run Cmd Get Info Err:" + str(e), False)
            sys.exit(1)

    #窗体绘制
    def setupUi(self):
        self.setObjectName("Ui_UsbTestMainFrm")
        self.resize(737, 453)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("IMAGE/usb.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.verticalLayout_9 = QtWidgets.QVBoxLayout(self)
        self.verticalLayout_9.setObjectName("verticalLayout_9")
        self.verticalLayout_6 = QtWidgets.QVBoxLayout()
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        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.horizontalLayout_3.addWidget(self.lbl_Logo)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_7 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setBold(True)
        font.setWeight(75)
        self.label_7.setFont(font)
        self.label_7.setStyleSheet("background-color: rgb(127, 127, 127);\n"
                                   "color: rgb(255, 255, 255);")
        self.label_7.setAlignment(QtCore.Qt.AlignCenter)
        self.label_7.setObjectName("label_7")
        self.horizontalLayout.addWidget(self.label_7)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.label = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setStyleSheet("background-color: rgb(127, 127, 127);\n"
                                 "color: rgb(255, 255, 255);")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.verticalLayout_3.addWidget(self.label)
        self.lbl_setUsb3Num = QtWidgets.QLabel(self)
        self.lbl_setUsb3Num.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_setUsb3Num.setObjectName("lbl_setUsb3Num")
        self.verticalLayout_3.addWidget(self.lbl_setUsb3Num)
        self.horizontalLayout.addLayout(self.verticalLayout_3)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label_5 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setBold(True)
        font.setWeight(75)
        self.label_5.setFont(font)
        self.label_5.setStyleSheet("background-color: rgb(127, 127, 127);\n"
                                   "color: rgb(255, 255, 255);")
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setObjectName("label_5")
        self.verticalLayout_4.addWidget(self.label_5)
        self.lbl_setUsb2Num = QtWidgets.QLabel(self)
        self.lbl_setUsb2Num.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_setUsb2Num.setObjectName("lbl_setUsb2Num")
        self.verticalLayout_4.addWidget(self.lbl_setUsb2Num)
        self.horizontalLayout.addLayout(self.verticalLayout_4)
        self.verticalLayout_2.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_8 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setBold(True)
        font.setWeight(75)
        self.label_8.setFont(font)
        self.label_8.setStyleSheet("background-color: rgb(170, 170, 127);\n"
                                   "color: rgb(255, 255, 255);")
        self.label_8.setAlignment(QtCore.Qt.AlignCenter)
        self.label_8.setObjectName("label_8")
        self.horizontalLayout_2.addWidget(self.label_8)
        self.verticalLayout_5 = QtWidgets.QVBoxLayout()
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.label_3 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("background-color: rgb(170, 170, 127);\n"
                                   "color: rgb(255, 255, 255);")
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.verticalLayout_5.addWidget(self.label_3)
        self.lbl_readUsb3Num = QtWidgets.QLabel(self)
        self.lbl_readUsb3Num.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_readUsb3Num.setObjectName("lbl_readUsb3Num")
        self.verticalLayout_5.addWidget(self.lbl_readUsb3Num)
        self.horizontalLayout_2.addLayout(self.verticalLayout_5)
        self.verticalLayout_7 = QtWidgets.QVBoxLayout()
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        self.label_9 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setBold(True)
        font.setWeight(75)
        self.label_9.setFont(font)
        self.label_9.setStyleSheet("background-color: rgb(170, 170, 127);\n"
                                   "color: rgb(255, 255, 255);")
        self.label_9.setAlignment(QtCore.Qt.AlignCenter)
        self.label_9.setObjectName("label_9")
        self.verticalLayout_7.addWidget(self.label_9)
        self.lbl_readUsb2Num_2 = QtWidgets.QLabel(self)
        self.lbl_readUsb2Num_2.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_readUsb2Num_2.setObjectName("lbl_readUsb2Num_2")
        self.verticalLayout_7.addWidget(self.lbl_readUsb2Num_2)
        self.horizontalLayout_2.addLayout(self.verticalLayout_7)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.verticalLayout.addLayout(self.verticalLayout_2)
        self.horizontalLayout_3.addLayout(self.verticalLayout)
        self.verticalLayout_6.addLayout(self.horizontalLayout_3)
        self.layout_teui = QtWidgets.QVBoxLayout()
        self.layout_teui.setObjectName("layout_teui")
        self.verticalLayout_6.addLayout(self.layout_teui)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.groupBox = QtWidgets.QGroupBox(self)
        font = QtGui.QFont()
        font.setPointSize(13)
        self.groupBox.setFont(font)
        self.groupBox.setObjectName("groupBox")
        self.verticalLayout_10 = QtWidgets.QVBoxLayout(self.groupBox)
        self.verticalLayout_10.setObjectName("verticalLayout_10")
        self.lbl_log = QtWidgets.QLabel(self.groupBox)
        font = QtGui.QFont()
        font.setPointSize(19)
        self.lbl_log.setFont(font)
        self.lbl_log.setStyleSheet("background-color: rgb(0, 0, 0);\n"
                                   "color: rgb(255, 170, 0);")
        self.lbl_log.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_log.setObjectName("lbl_log")
        self.verticalLayout_10.addWidget(self.lbl_log)
        self.horizontalLayout_4.addWidget(self.groupBox)
        self.verticalLayout_6.addLayout(self.horizontalLayout_4)
        self.verticalLayout_9.addLayout(self.verticalLayout_6)

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

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("HddTestMainFrm", "USBTest"))
        self.label_7.setText(_translate("HddTestMainFrm", "配置接口"))
        self.label.setText(_translate("HddTestMainFrm", "USB3.0测试数"))
        self.lbl_setUsb3Num.setText(_translate("HddTestMainFrm", "N/A"))
        self.label_5.setText(_translate("HddTestMainFrm", "USB2.0测试数"))
        self.lbl_setUsb2Num.setText(_translate("HddTestMainFrm", "N/A"))
        self.label_8.setText(_translate("HddTestMainFrm", "侦测接口"))
        self.label_3.setText(_translate("HddTestMainFrm", "USB3.0测试数"))
        self.lbl_readUsb3Num.setText(_translate("HddTestMainFrm", "N/A"))
        self.label_9.setText(_translate("HddTestMainFrm", "USB2.0测试数"))
        self.lbl_readUsb2Num_2.setText(_translate("HddTestMainFrm", "N/A"))
        self.groupBox.setTitle(_translate("HddTestMainFrm", "【日志】"))
        self.lbl_log.setText(_translate("HddTestMainFrm", "待测试"))

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

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

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

    # 定义一个函数使得函数窗口居中显示
    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.lbl_log.setStyleSheet("color:green;")
                self.logger.info(str(log))
            else:
                self.lbl_log.setStyleSheet("color:red;")
                self.logger.error(str(log))
            self.lbl_log.setText(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()
        readValue='usb2='+str(self.readUsb2Count)+'|'+'usb3='+str(self.readUsb3Count)
        self.UpdateJsonTestArgs(self.itemName, readValue, 'FAIL')
        sys.exit(1)

class Ui_Form(QWidget):
    #初始化
    #deviceId:硬件ID,portType:端口类型,读取的硬件地址,rBrand:读取的品牌规格,rSize:容量大小,rType:读取类型
    def __init__(self,deviceId,portType,rdevicePath,rBrand,rSize,rType):
    #def __init__(self):
        super().__init__()
        self.setupUi()

        #设置参数
        self.lbl_DeviceId.setText(deviceId)#设置硬件ID
        self.lbl_PortType.setText(portType)#端口类型/USB2.0或者USB3.0
        self.lbl_rDevicePath.setText(rdevicePath)#读取硬件地址
        self.lbl_rBrand.setText(rBrand)#读取厂商品牌规格
        self.lbl_rSize.setText(rSize)#读取容量大小
        self.lbl_rType.setText(rType)#读取端口类型


    #Ui初始化
    def setupUi(self):
        self.setObjectName("Form")
        self.resize(219, 142)
        self.gridLayout = QtWidgets.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout()
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.verticalLayout_9 = QtWidgets.QVBoxLayout()
        self.verticalLayout_9.setObjectName("verticalLayout_9")
        self.verticalLayout_10 = QtWidgets.QVBoxLayout()
        self.verticalLayout_10.setObjectName("verticalLayout_10")
        self.horizontalLayout_11 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_11.setObjectName("horizontalLayout_11")
        self.verticalLayout_12 = QtWidgets.QVBoxLayout()
        self.verticalLayout_12.setObjectName("verticalLayout_12")
        self.lbl_DeviceId = QtWidgets.QLabel(self)
        self.lbl_DeviceId.setStyleSheet("background-color: rgb(170, 170, 127);\n"
                                        "color: rgb(255, 255, 255);")
        self.lbl_DeviceId.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_DeviceId.setObjectName("lbl_DeviceId")
        self.verticalLayout_12.addWidget(self.lbl_DeviceId)
        self.lbl_PortType = QtWidgets.QLabel(self)
        self.lbl_PortType.setStyleSheet("background-color: rgb(170, 170, 127);\n"
                                        "color: rgb(255, 255, 255);")
        self.lbl_PortType.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_PortType.setObjectName("lbl_PortType")
        self.verticalLayout_12.addWidget(self.lbl_PortType)
        self.horizontalLayout_11.addLayout(self.verticalLayout_12)
        self.verticalLayout_10.addLayout(self.horizontalLayout_11)
        self.verticalLayout_9.addLayout(self.verticalLayout_10)
        self.horizontalLayout_3.addLayout(self.verticalLayout_9)
        self.gridLayout_2 = QtWidgets.QGridLayout()
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.groupBox_2 = QtWidgets.QGroupBox(self)
        self.groupBox_2.setObjectName("groupBox_2")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.groupBox_2)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.verticalLayout_6 = QtWidgets.QVBoxLayout()
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.label_3 = QtWidgets.QLabel(self.groupBox_2)
        self.label_3.setStyleSheet("background-color: rgb(255, 170, 0);")
        self.label_3.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_8.addWidget(self.label_3)
        self.lbl_rDevicePath = QtWidgets.QLabel(self.groupBox_2)
        self.lbl_rDevicePath.setObjectName("lbl_rDevicePath")
        self.horizontalLayout_8.addWidget(self.lbl_rDevicePath)
        self.verticalLayout_6.addLayout(self.horizontalLayout_8)
        self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_9.setObjectName("horizontalLayout_9")
        self.label_5 = QtWidgets.QLabel(self.groupBox_2)
        self.label_5.setStyleSheet("background-color: rgb(85, 170, 127);")
        self.label_5.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_9.addWidget(self.label_5)
        self.lbl_rBrand = QtWidgets.QLabel(self.groupBox_2)
        self.lbl_rBrand.setObjectName("lbl_rBrand")
        self.horizontalLayout_9.addWidget(self.lbl_rBrand)
        self.verticalLayout_6.addLayout(self.horizontalLayout_9)
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.label_7 = QtWidgets.QLabel(self.groupBox_2)
        self.label_7.setStyleSheet("background-color: rgb(255, 170, 127);")
        self.label_7.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_7.setObjectName("label_7")
        self.horizontalLayout_7.addWidget(self.label_7)
        self.lbl_rSize = QtWidgets.QLabel(self.groupBox_2)
        self.lbl_rSize.setObjectName("lbl_rSize")
        self.horizontalLayout_7.addWidget(self.lbl_rSize)
        self.verticalLayout_6.addLayout(self.horizontalLayout_7)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_9 = QtWidgets.QLabel(self.groupBox_2)
        self.label_9.setStyleSheet("background-color: rgb(0, 255, 0);\n"
                                   "background-color: rgb(255, 170, 255);")
        self.label_9.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_9.setObjectName("label_9")
        self.horizontalLayout_5.addWidget(self.label_9)
        self.lbl_rType = QtWidgets.QLabel(self.groupBox_2)
        self.lbl_rType.setObjectName("lbl_rType")
        self.horizontalLayout_5.addWidget(self.lbl_rType)
        self.verticalLayout_6.addLayout(self.horizontalLayout_5)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.verticalLayout_6.addLayout(self.horizontalLayout_6)
        self.horizontalLayout_4.addLayout(self.verticalLayout_6)
        self.gridLayout_3.addLayout(self.horizontalLayout_4, 0, 0, 1, 1)
        self.gridLayout_2.addWidget(self.groupBox_2, 0, 0, 1, 1)
        self.horizontalLayout_3.addLayout(self.gridLayout_2)
        self.verticalLayout_5.addLayout(self.horizontalLayout_3)
        self.gridLayout.addLayout(self.verticalLayout_5, 0, 0, 1, 1)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)

    #绘制UI控件
    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Form", "Form"))
        self.lbl_DeviceId.setText(_translate("Form", "N/A"))
        self.lbl_PortType.setText(_translate("Form", "N/A"))
        self.groupBox_2.setTitle(_translate("Form", "--【检测数据】--"))
        self.label_3.setText(_translate("Form", "DevicePath:"))
        self.lbl_rDevicePath.setText(_translate("Form", "N/A"))
        self.label_5.setText(_translate("Form", "品牌规格:"))
        self.lbl_rBrand.setText(_translate("Form", "N/A"))
        self.label_7.setText(_translate("Form", "容量:"))
        self.lbl_rSize.setText(_translate("Form", "N/A"))
        self.label_9.setText(_translate("Form", "类型:"))
        self.lbl_rType.setText(_translate("Form", "N/A"))

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

展示UI

文章来源:https://blog.csdn.net/u013934107/article/details/135282144
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。