单击菜单标题时连接功能

connect a function when menu title is clicked

我正在尝试查找打开的端口并将它们添加到我的菜单中。 现在,我成功地对我的菜单进行了操作(例如,"find ports"),并且仅当它被单击时 - 它才会连接到我的函数以获取所有空闲端口。 不幸的是,这不是我要找的。

我想单击菜单 标题,然后在我的菜单中获取所有端口。 下面是我的代码:

这是 GUI 部分:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(150, 150)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.portList = QtWidgets.QPushButton(self.centralwidget)
        self.portList.setGeometry(QtCore.QRect(10, 50, 65, 23))
        self.portList.setObjectName("portList")

        self.productMenu=QtWidgets.QMenu(self.centralwidget)
#        self.productMenu.addAction("Find Port") <-------- If I add this, then it works when I click on "Find Port"

        self.portList.setMenu(self.productMenu)

        MainWindow.setCentralWidget(self.centralwidget)

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





    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "GUI"))
        self.portList.setText(_translate("MainWindow", "Ports"))

这就是我 运行 我的职能所在:

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.productMenu.triggered.connect(self.findPort)

        self.ui.portList.clicked.connect(self.findPort)
        ###I tried both lines above, but it doesn't connect to the function###
    def findPort(self):
          comPorts = list(serial.tools.list_ports.comports())
          print("clicked!")
           for counter in comPorts:
               strPort=str(counter)
               print(strPort)
               self.ui.productMenu.addAction(strPort)

    def portClick(self,action):
        print(action.text())


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    application = ApplicationWindow()
    application.show()
    sys.exit(app.exec_())

如何通过按菜单标题获得 findport 连接功能,并立即使用空闲端口更新?

您必须使用 aboutToShow 信号:

self.ui.productMenu.aboutToShow.connect(self.findPort)