Solved How to write code to get the name/current text of a menu item?
-
@sdf1444 Simply use https://doc.qt.io/qt-5/qobject.html#objectName-prop to get object name as already suggested.
Like:self.combo.objectName()
-
But I thought "self.combo" refers to a combo box and not a menu item?
-
Hi,
You have to adapt to your code. You know where that menu is accessible.
-
Yes but not sure about the rest.
-
What rest ? @jsulm already provided information.
And what is exactly the goal of getting the name of the menu ?
-
"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
-
@sdf1444 Do you want the text or object name?
You should be more clear.
https://doc.qt.io/qt-5/qmenu.html#title-prop -
To add to @jsulm, since you are talking about menu item, you likely are looking for the QAction::text property.
-
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. Thetext
is the same but uses the text propertyTo 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.... -
When I mention "menu" I mean QMenu.
-
@sdf1444
OK. So where you gofileMenu.addAction(item)
it's thatQAction
you need to calltext()
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. -
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