Pre-select QMenu item

John F Sturtz john at sturtz.org
Sun Mar 3 00:21:51 GMT 2024


Hello good folks.

I think this is a relatively straightforward question.  But the issue is 
complicated by the fact that what I am trying to do works perfectly well 
(seemingly) in my small test program.  In my larger app, not so much.

I am creating a QMenu object on the fly and then using .exec() to 
display it as a popup.  What I would like to do is cause the first item 
in the menu to be already selected when it pops up.

I'd have thought this would be simple enough to accomplish, using 
.setActiveAction().  And indeed, in the small test program I wrote 
(which is in the zip file attached), it does seem to work as I expect. 
The pertinent code is:

             menu = QtWidgets.QMenu()
             for s in ('Foo', 'Bar', 'Baz'):
menu.addAction(QtGui.QIcon('account.png'), s)
menu.setActiveAction(menu.actions()[0])
menu.exec(self.mapToGlobal(QtCore.QPoint(20, 20)))

In my smaller test program, this does just what I expect:  When the menu 
pops up, the first item is selected.

Here's the rub:  When I put essentially the exact same code into my 
larger app, it behaves oddly.  The first time I display the popup menu, 
it doesn't work.  The popup menu displays, but it does not select the 
first item as I would expect.  The next time I display the popup, it 
does work.  And every time thereafter, until the app shuts down.

I realize this is a bit of a slippery question, because I can't post the 
code that doesn't work -- only the code that does.  Apparently, 
something that is going on with the larger app is messing with this.  
But I'm wondering if anyone has any ideas as to why this might be the 
case, or what I might try to get around it.

Thanks!

/John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20240302/878b7ade/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test.zip
Type: application/x-zip-compressed
Size: 3081 bytes
Desc: not available
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20240302/878b7ade/attachment.bin>


More information about the PyQt mailing list