[单击菜单标题时连接功能

问题描述 投票:1回答:1

我正在尝试查找打开的端口并将其添加到菜单中。现在,我成功对菜单执行了操作(例如,“查找端口”),并且只有在单击该菜单时,它才会连接到我的获取所有可用端口的函数。不幸的是,这不是我想要的。

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

这是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功能连接,并立即使用空闲端口更新它?

python pyqt pyqt5 qpushbutton qmenu
1个回答
2
投票

您必须使用aboutToShow信号:

aboutToShow
© www.soinside.com 2019 - 2024. All rights reserved.