Original | PYQT5 | programming experience | pit climbing | sharing | 4|python advanced operation: multiple controls use the same function entry

Keywords: Python Pycharm SQLite PyQt5

         When we program PYQT5, when the interface design is completed, we usually need to correspond the control to the corresponding function events in the code one by one. If there are few controls, it may be nothing. However, with the gradual increase of requirements and functions of subsequent software projects, it is very unfavorable to subsequent maintenance, and this way is not conducive to subsequent expansion.

         If you want to better solve this problem, you need to have a better architecture design at the beginning of the design. A better way is to call a unified entry for multiple homogeneous or same type controls, and only maintain fewer program entries for subsequent maintenance to realize data separation.

The following is an example of my daily programming, which is hereby recorded for future reference and learning.

Test scenario:

Multiple button controls perform DFU upgrade operations of different versions.

Analysis steps:

1. At present, there are less than 10 versions that need to be updated. Later, they can be expanded according to the needs of users;

2. The version number can be configured in the configuration file. When the program is initialized, the configuration file can be read and displayed as the button control name;

3. By default, these button controls are invisible; If the version number is not empty and the version number is valid, the corresponding button control will be displayed on the program interface;

4. Multiple buttons call the same entry function, obtain the name of the currently clicked button according to the user's click operation, execute the corresponding function, and perform DFU upgrade operation, so as to realize that multiple buttons call the same entry function, but different functions can be realized automatically;

Function call instance

#Button connection function
self.toolButton_BatchRun_DFU_1.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_2.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_3.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_4.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_5.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_6.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_7.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_8.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_9.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_10.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_11.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_12.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_13.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_14.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_15.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_16.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_17.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_18.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_19.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_20.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_21.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_22.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_23.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_24.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_25.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_26.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_27.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_28.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_29.clicked.connect(self.BatchRun_g2_DFU)  # Button link-
self.toolButton_BatchRun_DFU_30.clicked.connect(self.BatchRun_g2_DFU)  # Button link-

Concrete implementation function

    def BatchRun_g2_DFU(self):
        global UserMode
        global Bridge_BT_ID
        if UserMode != 1:
            self.logOut("The software is not registered or has expired. Please register and reopen the software...")
            return
        
        
        button = w.sender()
        button_name=button.objectName()
        print('button={}'.format(button))
        print('button_name={}'.format(button_name))
        
        button_title = button.text()
        self.logOut('button_title={}'.format(button_title))

        
        ota_name=''
        try:
            ota_name='ota'+str(int(str(button_title).split('(')[1].replace(')','').replace('.','')))
            self.logOut('ota_name={}'.format(ota_name))
            
            #Judge version number
            if 'ota' not in ota_name:
                return 0
        except BaseException as get_err:
            self.logOut('button_title={},Error getting version number...'.format(button_title))
            return -1
            
      
        
        if not button.isCheckable():
            if self.dialog_YesNo('Operation in progress:{},Whether to proceed DFU to update?\n Update object:\n{}\nDFU Package name:{}'.format(Bridge_BT_ID,button_title,ota_name)) == 1:
                threading.Thread(target=self.BatchRun_g2_DFU_thread,args=(ota_name,button_title,Bridge_BT_ID,)).start()
        
    def BatchRun_g2_DFU_thread(self,ota_name='',button_title='',Bridge_BT_ID=''):
        global folderName
        global RunFlag

        try:
            self.save_user_config()
            # Get the list of lockids that need to be added
    
            LockID_List = self.get_Batch_LockList()
    
            self.logOut('-' * 100)

            WaitTimes_DFU  = int(self.spinBox_WaitTimes_DFU.value())
            SleepTime_DFU  = int(self.spinBox_SleepTime_DFU.value())
            RunFlag = 1
            # for runCount in range(1, RunTimes + 1):
            if RunFlag == 0:
                return -1
    
            self.logOut('-' * 100)
    
            self.logOut('button_title= {}'.format(button_title))
            self.logOut('Start execution BatchRun_g2_DFU_thread operation,Bridge_BT_ID= {},ota_name= {}'.format(Bridge_BT_ID,ota_name))
    
            startTime = IDP_EFG_requests_HRD.getTime(1)
            # Pin_Input = self.textEdit_DeletePassword_Show.toPlainText()
            
            result = IDP_EFG_requests_HRD.bridge_g2_DFU(str(ota_name),Bridge_BT_ID)
            self.logOut('Request Return results=\n{}'.format(IDP_EFG_requests_HRD.show))
            self.logOut('Command return results= {}'.format(result))
            endTime = IDP_EFG_requests_HRD.getTime(1)
            spent_times = IDP_EFG_requests_HRD.date_time_count_ms(endTime, startTime)
            self.logOut('Start execution time= {} ,End execution time= {} ,Total time spent= {} second'.format(startTime, endTime, spent_times))
            self.logOut('-' * 100)
    
            folderName = "\\API_test_Logs"
            SaveLogFileName = "\\Bridge_BatchRun_g2_DFU_thread_log.log"
            self.writeFile(self.getDT() + " [info] " + "--------" + "\n", folderName, SaveLogFileName)
            self.writeFile(self.getDT() + " [info] " + "button_title= {} ".format(button_title) + "\n", folderName, SaveLogFileName)
            self.writeFile(self.getDT() + " [info] " + 'Start execution,Bridge_BT_ID= {} of DFU operation,ota_name= {}'.format(Bridge_BT_ID,ota_name) + "\n", folderName,SaveLogFileName)
            self.writeFile(self.getDT() + " [info] " + "Return results= {}".format(str(result)) + "\n", folderName,SaveLogFileName)
            self.writeFile(self.getDT() + " [info] " + 'Start execution time= {} ,'.format(startTime) + 'End execution time= {} ,'.format(endTime) + 'Total time spent= {} second'.format(spent_times) + "\n", folderName, SaveLogFileName)
    
            
            self.logOut('-' * 100)
            self.logOut_dfu(string_color('-' * 100, '0000FF'))
            self.logOut('Bridge_BT_ID={},start DFU Operation, DFU In the process, WIFI The green light will flash continuously. Please wait for the program to complete automatically Bridge Will restart automatically...'.format(Bridge_BT_ID))
            self.logOut_dfu('Bridge_BT_ID={},start DFU Operation, DFU In the process, WIFI The green light will flash continuously. Please wait for the program to complete automatically Bridge Will restart automatically...'.format(Bridge_BT_ID))
            self.logOut('Bridge_BT_ID={},Please wait for restart WIFI Continue after the light is normally on and green...'.format(Bridge_BT_ID))
            self.logOut_dfu('Bridge_BT_ID={},Please wait for restart WIFI Continue after the light is normally on and green...'.format(Bridge_BT_ID))
            
            for r in range(1, WaitTimes_DFU+1):
                if RunFlag == 0:
                    return 0
                self.logOut(string_color('Bridge_BT_ID={},Wait 30 seconds, second {}/{} second...'.format(Bridge_BT_ID,r,WaitTimes_DFU),'0000FF'))
                self.logOut_dfu(string_color('Bridge_BT_ID={},Wait 30 seconds, second {}/{} second...'.format(Bridge_BT_ID,r,WaitTimes_DFU),'0000FF'))
                self.logOut(string_color('Bridge_BT_ID={},Current total waiting {} second...'.format(Bridge_BT_ID,(r-1)*30),'FF00FF'))
                self.logOut_dfu(string_color('Bridge_BT_ID={},Current total waiting {} second...'.format(Bridge_BT_ID,(r-1)*30),'FF00FF'))
                sleep(int(SleepTime_DFU))
                
            
            DFU_endTime = IDP_EFG_requests_HRD.getTime(1)
            DFU_spent_times = IDP_EFG_requests_HRD.date_time_count_ms(DFU_endTime, startTime)

            self.logOut('-' * 100)
            self.logOut('Start execution time= {} ,End execution time= {} ,Total time spent= {} second'.format(startTime, DFU_endTime, DFU_spent_times))
            self.logOut_dfu('Start execution time= {} ,End execution time= {} ,Total time spent= {} second'.format(startTime, DFU_endTime, DFU_spent_times))
            
            self.logOut(string_color('DFU Completed,Bridge_BT_ID={}...'.format(Bridge_BT_ID),'00FFFF'))
            self.logOut_dfu(string_color('DFU Completed,Bridge_BT_ID={}...'.format(Bridge_BT_ID),'00FFFF'))
            
            self.logOut(string_color('Bridge_BT_ID={},Please wait for the device restart to complete...'.format(Bridge_BT_ID),'00FFFF'))
            self.logOut_dfu(string_color('Bridge_BT_ID={},Please wait for the device restart to complete...'.format(Bridge_BT_ID),'00FFFF'))
            
            self.logOut(string_color('-'*100,'0000FF'))
            self.logOut_dfu(string_color('-'*100,'0000FF'))
            self.logOut('-' * 100)
        except Exception as e:
            self.logOut('BatchRun_g2_DFU_thread Failure, failure information= {}'.format(e))

Function description

The main implementation functions are:

        button = w.sender()
        button_name=button.objectName()
        print('button={}'.format(button))
        print('button_name={}'.format(button_name))
        
        button_title = button.text()
        self.logOut('button_title={}'.format(button_title))

        
        ota_name=''
        try:
            ota_name='ota'+str(int(str(button_title).split('(')[1].replace(')','').replace('.','')))
            self.logOut('ota_name={}'.format(ota_name))
            
            #Judge version number
            if 'ota' not in ota_name:
                return 0
        except BaseException as get_err:
            self.logOut('button_title={},Error getting version number...'.format(button_title))
            return -1
            
      
        
        if not button.isCheckable():
            if self.dialog_YesNo('Operation in progress:{},Whether to proceed DFU to update?\n Update object:\n{}\nDFU Package name:{}'.format(Bridge_BT_ID,button_title,ota_name)) == 1:
                threading.Thread(target=self.BatchRun_g2_DFU_thread,args=(ota_name,button_title,Bridge_BT_ID,)).start()

Posted by mwl707 on Mon, 22 Nov 2021 18:49:10 -0800