思路就是继承QComboBox,声明一个新的信号,重写showPopup函数
class my_combo_box(QComboBox):
popup = pyqtSignal()
def showPopup(self) -> None:
super(my_combo_box, self).showPopup()
self.popup.emit()
在ui class中使用新的combo_box
self.usbd_cdc_combo = my_combo_box()
在MainWindow中连接槽函数,实现槽函数
self.usbd_cdc_combo.popup.connect(self.scan_virtual_com_port)
self.usbd_cdc_combo.currentTextChanged[str].connect(self.get_current_serial_port)
在自己的某个函数中一直调用scan_virtual_com_port函数。
def scan_virtual_com_port(self) -> None:
new_name_list = []
scan_port_list = []
uart_port_num = QSerialPortInfo.availablePorts()
for info in uart_port_num:
uart_str_name = info.portName().split()
uart_str_desc = info.description()
if 'GD32' in uart_str_desc:
scan_port_list.append(uart_str_name[0] + ' ' + uart_str_desc)
if len(scan_port_list) > 0:
for i in scan_port_list:
if i not in new_name_list:
new_name_list.append(i)
else:
scan_port_list = new_name_list
if scan_port_list != self.my_dict['usbd_cdc_list']:
if self.my_dict['scan_flags'] == 0:
self.my_dict['usbd_cdc_list'] = scan_port_list
self.usbd_cdc_combo.clear()
for i in self.my_dict['usbd_cdc_list']:
self.usbd_cdc_combo.addItem(i)
self.my_dict['scan_flags'] = 1
else:
s1 = set(scan_port_list)
s2 = set(self.my_dict['usbd_cdc_list'])
if len(s1) > len(s2):
l1 = list(s1 - s2)
for i in l1:
self.my_dict['usbd_cdc_list'].append(i)
self.usbd_cdc_combo.addItem(i)
elif len(s1) < len(s2):
l1 = list(s2 - s1)
for i in l1:
lost_index = self.my_dict['usbd_cdc_list'].index(i)
self.usbd_cdc_combo.removeItem(lost_index)
self.my_dict['usbd_cdc_list'].remove(i)
port_temp_list = self.usbd_cdc_combo.currentText().split(" ")
self.my_dict['current_port'] = port_temp_list[0]
def get_current_serial_port(self, index: str):
port_temp_list = self.usbd_cdc_combo.currentText().split(" ")
if self.my_dict['current_port'] != port_temp_list[0]:
if self.my_dict['shdn'] == 0:
# do something
pass