我试图单击QComboBox以获得端口列表,并调整其大小,以便可以看到完整的端口名称,但是我遇到了一些问题: 我试图在“单击”上连接组合框,但是它不起作用,因此我尝试使用mousepressedevent,但是当我运行脚本时,即使不按该组合键,它也会直接转到该函数。 如果用户单击组合框或其下拉列表之外的任何位置,我也想再次使组合框变小。
这是我的代码: 这部分是GUI代码:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(780, 590)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.portList = QtWidgets.QComboBox(self.centralwidget)
self.portList.setGeometry(QtCore.QRect(50, 50, 50, 25))
self.portList.setObjectName("portList")
MainWindow.setCentralWidget(self.centralwidget)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
这是实际代码的一部分:
from PyQt5 import QtWidgets, QtCore, QtGui
from test1 import Ui_MainWindow
import serial.tools.list_ports
import sys
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super(ApplicationWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.portList.mousePressEvent=self.findPort()
# self.ui.portList.clicked.connect(self.findPort) <---- this does not work
def findPort(self):
comPorts = list(serial.tools.list_ports.comports()) # get a list of all devices connected through serial port
self.i=0
for counter in comPorts:
strPort=str(counter)
self.ui.portList.addItem("")
self.ui.portList.setItemText(self.i,strPort)
self.i=self.i+1
if self.i==0:
self.ui.portList.addItem("")
self.ui.portList.setItemText(0,"No Ports!")
else:
self.ui.portList.resize(500,25)
def clickedOutside(self): ####<---- not sure how to connect to this func (when clicked outside of the list)
self.ui.portList.resize(50,25)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
application = ApplicationWindow()
application.show()
sys.exit(app.exec_())
如果有人有想法,将不胜感激。