Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. How to write code to get the name/current text of a menu item?
Forum Updated to NodeBB v4.3 + New Features

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

Scheduled Pinned Locked Moved Solved Qt for Python
19 Posts 6 Posters 4.1k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S sdf1444

    @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_())
    
    jsulmJ Offline
    jsulmJ Offline
    jsulm
    Lifetime Qt Champion
    wrote on last edited by
    #6

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

    self.combo.objectName()
    

    https://forum.qt.io/topic/113070/qt-code-of-conduct

    S 1 Reply Last reply
    1
    • jsulmJ jsulm

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

      self.combo.objectName()
      
      S Offline
      S Offline
      sdf1444
      wrote on last edited by
      #7

      @jsulm

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

      1 Reply Last reply
      0
      • SGaistS Offline
        SGaistS Offline
        SGaist
        Lifetime Qt Champion
        wrote on last edited by
        #8

        Hi,

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

        Interested in AI ? www.idiap.ch
        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

        S 1 Reply Last reply
        0
        • SGaistS SGaist

          Hi,

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

          S Offline
          S Offline
          sdf1444
          wrote on last edited by
          #9

          @SGaist

          Yes but not sure about the rest.

          1 Reply Last reply
          0
          • SGaistS Offline
            SGaistS Offline
            SGaist
            Lifetime Qt Champion
            wrote on last edited by
            #10

            What rest ? @jsulm already provided information.

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

            Interested in AI ? www.idiap.ch
            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

            S 1 Reply Last reply
            0
            • SGaistS SGaist

              What rest ? @jsulm already provided information.

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

              S Offline
              S Offline
              sdf1444
              wrote on last edited by
              #11

              @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

              jsulmJ JonBJ 2 Replies Last reply
              0
              • S sdf1444

                @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

                jsulmJ Offline
                jsulmJ Offline
                jsulm
                Lifetime Qt Champion
                wrote on last edited by
                #12

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

                https://forum.qt.io/topic/113070/qt-code-of-conduct

                1 Reply Last reply
                1
                • SGaistS Offline
                  SGaistS Offline
                  SGaist
                  Lifetime Qt Champion
                  wrote on last edited by
                  #13

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

                  Interested in AI ? www.idiap.ch
                  Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                  S 1 Reply Last reply
                  1
                  • S sdf1444

                    @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

                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on last edited by JonB
                    #14

                    @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....

                    1 Reply Last reply
                    0
                    • SGaistS SGaist

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

                      S Offline
                      S Offline
                      sdf1444
                      wrote on last edited by
                      #15

                      @SGaist

                      When I mention "menu" I mean QMenu.

                      JonBJ Pablo J. RoginaP 2 Replies Last reply
                      0
                      • S sdf1444

                        @SGaist

                        When I mention "menu" I mean QMenu.

                        JonBJ Offline
                        JonBJ Offline
                        JonB
                        wrote on last edited by JonB
                        #16

                        @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?

                        1 Reply Last reply
                        1
                        • S sdf1444

                          @SGaist

                          When I mention "menu" I mean QMenu.

                          Pablo J. RoginaP Offline
                          Pablo J. RoginaP Offline
                          Pablo J. Rogina
                          wrote on last edited by Pablo J. Rogina
                          #17

                          @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.

                          Upvote the answer(s) that helped you solve the issue
                          Use "Topic Tools" button to mark your post as Solved
                          Add screenshots via postimage.org
                          Don't ask support requests via chat/PM. Please use the forum so others can benefit from the solution in the future

                          S 1 Reply Last reply
                          3
                          • Pablo J. RoginaP Pablo J. Rogina

                            @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.

                            S Offline
                            S Offline
                            sdf1444
                            wrote on last edited by
                            #18

                            @Pablo-J-Rogina

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

                            Pablo J. RoginaP 1 Reply Last reply
                            0
                            • S sdf1444

                              @Pablo-J-Rogina

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

                              Pablo J. RoginaP Offline
                              Pablo J. RoginaP Offline
                              Pablo J. Rogina
                              wrote on last edited by
                              #19

                              @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

                              Upvote the answer(s) that helped you solve the issue
                              Use "Topic Tools" button to mark your post as Solved
                              Add screenshots via postimage.org
                              Don't ask support requests via chat/PM. Please use the forum so others can benefit from the solution in the future

                              1 Reply Last reply
                              2

                              • Login

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • Users
                              • Groups
                              • Search
                              • Get Qt Extensions
                              • Unsolved