Peculiar behavior trying to set active menu item
Charles
peacech at gmail.com
Thu Mar 6 01:15:55 GMT 2025
If you look at
https://codebrowser.dev/qt6/qtbase/src/widgets/widgets/qmenu.cpp.html#_ZN5QMenu10timerEventEP11QTimerEvent,
QMenu has a timerEvent. This resets the highlight.
What you can do is store the active item in an attribute and reselect it
after the timerEvent
def timerEvent(self, event):
super().timerEvent(event)
if self._active_action:
self.setActiveAction(self._active_action)
On Thu, Mar 6, 2025 at 4:03 AM John Sturtz <john at sturtz.org> wrote:
> This probably qualifies as one of those things it occurred to me I
> *should* be able to do. So then, of course, I set out to try it. And it
> doesn't seem to work quite as I expect. (Perhaps the best answer is "Don't
> do that"?)
>
> I've got a QToolButton object with a menu attached to it. My idea is to
> implement menu shortcut keys. So if you hit an alphabetic key, it makes
> active the first item in the menu that starts with that letter. If you hit
> the same key again, it takes you to the next matching item. And so on.
> (And if you get to the last, it wraps around and re-selects the first
> again).
>
> To that end, I create a custom Menu class derived from QMenu. The
> button's main menu is an object of the Menu class. Also, one item in the
> main menu has a submenu, which is also an instance of Menu. I
> re-implement the Menu class .keyPressEvent() method, and when matching
> letters are hit, set the active menu item with .setActiveAction().
>
> Everything seems to work fine until I display the submenu. Then things
> turn flaky.
>
> I have a small reproducible example attached. 'Flaky' behavior can be
> observed (at least, on my machine) as follows:
>
> Click the button, and a menu of some cities displays. Hit 'A', 'B', 'H',
> or 'L' to select cities starting with those letters (the non-submenu
> items), and all works as expected.
>
> Now hit 'D' to select Denver. It makes that item active and displays the
> submenu. Hit the left arrow to make the submenu disappear. Then hit 'A'
> to select Anchorage. It highlights ... for about a second. And then the
> selection background disappears.
>
> Any ideas why this would be? My first thought was that Qt maintains some
> state information regarding which menu item is active, and the main menu
> and submenu are interfering with each other. It is true that the are the
> same class. But they are separate instances of that class, so I'd have
> expected they'd be able to function independently of one another.
>
> Any thoughts appreciated.
>
> Thanks!
>
> /John
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20250306/3b78ec34/attachment.htm>
More information about the PyQt
mailing list