Receive value from MenuItem
-
Hello, I am trying to use a menu to set a value to a variable. Most of the ways I have tried the variable remains undefined. Specifically, I am trying to show a menu to users when they click the screen and then set a specific value to the variable based on the option the user chooses.
My current code looks like:id: mouseArea1 property var testValue; onClicked: { menu.popup() console.log(testValue); } Menu { id: menu MenuItem { text: "Option1" onTriggered: { mouseArea1.testValue= "25" } } }
This almost works. The first time users select a value the output is still undefined. The second time they select a value then the value of the last option they chose is output. I tried using 'var testValue = menu.popup()' and then within the onTriggered 'return "25"' however this always output undefined.
I cannot tell if the value is not being updated quickly enough or if it just isn't being updated successfully.
Any suggestions on how to achieve this goal, of setting a value from a menu item, would be greatly appreciated. Thank you -
Your code should be fine. I think that the console.log() command is just in the wrong place.
If I understood correctly, there are two user interactions involved. The first one is the click on the mouse area, which opens the menu. The second one is a click on a particular menu item, which actually sets the test value.
Let's say you are performing the first interaction for the first time. At this point, the variable hasn't been set as you haven't clicked on a menu item yet. That is why the output of the console.log() command will be undefined. Then, you click on a menu item, which sets the variable. However, you won't be able to see the change until the menu is closed and you perform another click on the mouse area to make the menu pop up again.
I think you'll see that your code works if you move the console.log() command to a different place:
id: mouseArea1 property var testValue; onClicked: { menu.popup(); } Menu { id: menu MenuItem { text: "Option1" onTriggered: { mouseArea1.testValue= "25"; console.log(mouseArea1.testValue); } } }
I don't know how many menu items you have in your actual code. Doing it this way, you'd need to add the same line to the onTriggered() signal handlers on all MenuItem instances, which could be annoying and bloat your code unnecessarily. So I'd suggest doing this instead:
id: mouseArea1 property var testValue; onClicked: { menu.popup(); } Menu { id: menu MenuItem { text: "Option1" onTriggered: { mouseArea1.testValue= "25"; } } onClosed: { console.log(mouseArea1.testValue); } }
I am assuming that the menu is closed once you hit a menu item. The code above logs the variable once the menu emits a closed() signal. I haven't tried it myself, but it should work. :)