Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to write code to get the name/current text of a menu item?



  • Hi

    I was wondering how do i write the code to get the name/current text of a menu item. I want it with a variable "self.fileName_UI =".

    Thanks



  • @sdf1444 as mentioned before what you need is the QAction::text property.
    And given that you're connecting lots of QAction objects (the items in your "Devices" menu) to the same slot, see below:

    for item in f:
    deviceImport = fileMenu.addAction(item)
    deviceImport.triggered.connect(self.importbutton)

    then in the slot you need to identify the signal sender to get a reference to the proper QAction, and get its text value (the device name you're looking for...). Something like this (code not tested)

    def importbutton(self):
        sender = self.sender()
        selectedDevice = sender.text()
    ...
    

    Look for code snippet eventsource.py in this example about signals & slots.



  • The name can be extracted from the objectName property of the QAction that represents the menu item. The rext is the same but uses the text property



  • @VRonin Thanks but how do I write this?


  • Lifetime Qt Champion

    @sdf1444 said in How to write code to get the name/current text of a menu item?:

    Thanks but how do I write this?

    In a text editor...
    Sorry, but how do you expect to get a better answer if you do not provide information needed?
    Where and in which context do you want to get the name and current text?
    Post the code where you want to do this.



  • @jsulm

    Hi

    So below is the code and in there is a variable "self.fileName_UI =" but it is for getting the text for a combo box. I want it to be changed so that it gets the text for a menu item. I am not sure how to write this.

    Thanks

    import paho.mqtt.client as mqtt
    import os
    import sys
    import PyQt5
    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import *
    from PyQt5 import QtWidgets, uic, QtCore
    from mqtt import *
    import json
    import time
    
    if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
    	PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
    if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
    	PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self,parent = None):
            QMainWindow.__init__(self)
            super(MainWindow, self).__init__(parent)
            self.mdi = QMdiArea()
            self.setCentralWidget(self.mdi)
    
            self.setMinimumSize(QSize(800, 600))
            self.setWindowTitle("PyQt button example - pythonprogramminglanguage.com")
    
            client = device()
            client.run()
    
            client.loop_start()
            print("Connected to broker")
            time.sleep(1)
            print("Subscribing to topic", "microscope/light_sheet_microscope/UI/devices")
            client.subscribe("microscope/light_sheet_microscope/UI/devices")
            print("Publishing message to topic", "microscope/light_sheet_microscope/UI/devices")
            client.publish("microscope/light_sheet_microscope/UI/devices", json.dumps({"type": "system", "payload":{"cmd": "get all devices"}}, indent=2))
            time.sleep(1)
            
            pybutton = QPushButton('Add device', self)
    
            pybutton.clicked.connect(self.importbutton)
    
            pybutton.move(100, 400)
            pybutton.resize(150, 32)
            # pybutton.hide()
    
            self.combo = QComboBox(self)        
            self.combo.move(100,350)
            self.combo.resize(100, 32)
            # self.combo.hide()                        
    
            menubar = self.menuBar()
            fileMenu = menubar.addMenu('Devices')
    
            def readFile(fname):
                try:
                    with open(fname, "r") as f:
                        for item in f:
                            deviceImport = fileMenu.addAction(item)
                            deviceImport.triggered.connect(self.importbutton)       
    
                            # self.combo.addItem(item, self.importbutton)
                except:
                    print("No devices active")
            readFile("list_of_device(s)_currently_active.txt") 
        
        def importbutton(self):
            if not os.path.exists("laser.ini"):
                client = device()
                client.run()
    
                client.loop_start()
                print("\n" + "Connected to broker")
                time.sleep(1)
                print("Subscribing to topic", "microscope/light_sheet_microscope/UI/add device")
                client.subscribe("microscope/light_sheet_microscope/UI/add device")
                print("Publishing message to topic", "microscope/light_sheet_microscope/UI/add device")
                client.publish("microscope/light_sheet_microscope/UI/add device", json.dumps({"type": "system", "payload":{"cmd": "init device panel"}}, indent=2))
                time.sleep(1)
                client.loop_stop()        
                self.fileName_UI = self.combo.currentText()
                self.loadGUI()
                print("Device panel initialised" + "\n")
            else:
                if os.path.exists("laser.ini"):
                    client = device()
                    client.run()
    
                    client.loop_start()
                    print("\n" + "Connected to broker")
                    time.sleep(1)
                    print("Subscribing to topic", "microscope/light_sheet_microscope/UI/laser")
                    client.subscribe("microscope/light_sheet_microscope/UI/laser")
                    print("Publishing message to topic", "microscope/light_sheet_microscope/UI/laser")
                    client.publish("microscope/light_sheet_microscope/UI/laser", json.dumps({"type": "device", "payload":{"name": "laser", "cmd": "set config"}}, indent=2))
                    time.sleep(1)
                    client.loop_stop()
                    self.fileName_UI = self.combo.currentText()
                    self.loadGUI()
                    print("Laser config set" + "\n")
    
        def loadGUI(self):
            module = __import__(self.fileName_UI.rstrip("\n"))
            my_class = getattr(module, "SubWindow")
            
            sub = QMdiSubWindow()
            
            sub.setWidget(my_class())
            sub.setWindowTitle(self.fileName_UI)
            self.mdi.addSubWindow(sub)
            sub.show()
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        mainWin = MainWindow()
        mainWin.show()
        # publishedMessage = mainWin.getGUIFilename()
        sys.exit(app.exec_())
    

  • Lifetime Qt Champion

    @sdf1444 Simply use https://doc.qt.io/qt-5/qobject.html#objectName-prop to get object name as already suggested.
    Like:

    self.combo.objectName()
    


  • @jsulm

    But I thought "self.combo" refers to a combo box and not a menu item?


  • Lifetime Qt Champion

    Hi,

    You have to adapt to your code. You know where that menu is accessible.



  • @SGaist

    Yes but not sure about the rest.


  • Lifetime Qt Champion

    What rest ? @jsulm already provided information.

    And what is exactly the goal of getting the name of the menu ?



  • @SGaist

    "self.combo.objectName()" doesnt work within my code. I need a way to get text of a menu item because the menu item refers to a python file in my current directory that I want to import.

    Thanks


  • Lifetime Qt Champion

    @sdf1444 Do you want the text or object name?
    You should be more clear.
    https://doc.qt.io/qt-5/qmenu.html#title-prop


  • Lifetime Qt Champion

    To add to @jsulm, since you are talking about menu item, you likely are looking for the QAction::text property.



  • @sdf1444

    self.combo.objectName()" doesnt work within my code. I need a way to get text of a menu item

    Which is why @VRonin originally replied to you

    The name can be extracted from the objectName property of the QAction that represents the menu item. The text is the same but uses the text property

    To be clear, your code does not seem to use a QAction anywhere, I think you need to read up on that whole class (https://doc.qt.io/qt-5/qaction.html).

    But now I am getting confused. Sometimes you talk about menu, which we are taking as a QMenu, and sometimes you talk about a combobox, QCombobox. I'm wondering whether by "menu" you mean a combobox, but I'm not sure....



  • @SGaist

    When I mention "menu" I mean QMenu.



  • @sdf1444
    OK. So where you go fileMenu.addAction(item) it's that QAction you need to call text() on to retrieve its text at a later date, which I believe is what you are asking.

    Just as P.S.: the device names you're reading from file won't have an & in them, will they?



  • @sdf1444 as mentioned before what you need is the QAction::text property.
    And given that you're connecting lots of QAction objects (the items in your "Devices" menu) to the same slot, see below:

    for item in f:
    deviceImport = fileMenu.addAction(item)
    deviceImport.triggered.connect(self.importbutton)

    then in the slot you need to identify the signal sender to get a reference to the proper QAction, and get its text value (the device name you're looking for...). Something like this (code not tested)

    def importbutton(self):
        sender = self.sender()
        selectedDevice = sender.text()
    ...
    

    Look for code snippet eventsource.py in this example about signals & slots.



  • @Pablo-J-Rogina

    Thank you so much!! This has worked for me.



  • @sdf1444 said in How to write code to get the name/current text of a menu item?:

    This has worked for me.

    Ok, so:
    Upvote the answer(s) that helped you to solve the issue
    Use the "Topic Tools" button to mark your post as Solved


Log in to reply