PyQT:重写QComboBox控件,添加click信号
痛点:
在读取电脑所有 COM 口时希望在点击 combobox 下拉框时能自动刷新列表
现状:
combobox 内置的信号没有 click 相关的动作
解决:
通过重写 combobox 中的鼠标点击事件进行实现
# -*- coding: utf-8 -*-
import sys
from PySide2 import QtCore, QtGui
from PySide2.QtWidgets import *
import serial
import serial.tools.list_ports
class MyComboBoxControl(QComboBox):
clicked = QtCore.Signal() # 自定义信号
def __init__(self, Parent=None):
super(MyComboBoxControl, self).__init__(Parent) # 调用父类的初始化方法
def mousePressEvent(self, event: QtGui.QMouseEvent) -> None: # 重写鼠标按下事件
if event.button() == QtCore.Qt.LeftButton: # 当鼠标左键单击时
self.clicked.emit() # 发射信号
QComboBox.showPopup(self) # 弹出下拉框
class WinForm(QWidget):
# 自定义信号,不带参数
button_clicked_signal = QtCore.Signal()
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle('Select Com Port')
self.combobox = MyComboBoxControl(self)
self.combobox.addItems(['COM1'])
self.combobox.setGeometry(QtCore.QRect(150, 20, 351, 51))
self.resize(700, 150)
# 接收信号,连接到自定义槽函数
self.combobox.clicked.connect(self.setComPort)
def setComPort(self):
# QMessageBox.information(self, 'Pop messgae', 'OK')
self.combobox.clear()
plist = list(serial.tools.list_ports.comports())
if len(plist) <= 0:
self.combobox.addItem('No Com Port')
else:
self.combobox.addItems('COM'+ i for i in plist)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = WinForm()
win.show()
sys.exit(app.exec_())