Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing a QMenu within multiple Qmenu

Hi all,

    I have some code generating a dynamically filled QMenu depending on some data (I will call it thisMenu). The QMenu thisMenu is created, taking some "main" QWidget as parent and is added to a QMenuBar within this QWidget (menuBar.addMenu(&thisMenu). Latter on, I want the user to be able of accessing thisMenu from a context menu (the user right click on some portion of the QWidget, which pops a QMenu (called contextMenu) with some actions, and the previous QMenu as a sub-menu).

    If I reuse the QMenu that I first created with contextMenu.addMenu(&thisMenu) I find out that, even if contextMenu pops at the right global position, thisMenu is always translated to some other position and appearing sometimes above, sometimes under contextMenu.

    I can test that this is linked to the parenting chain : thisMenu is not a child of contextMenu, if I create it a child of contextMenu, everything is fine. Is there a way of cleanly handling this case without recreating a QMenu similar to thisMenu, or changing the parent of thisMenu; i.e. reusing thisMenu in both QMenuBar and in some context menu/QMenu? In other what is the proper way of handling parenting chain for QMenu and sharing QMenu?

    Thank you,

like image 418
Arkh Avatar asked Aug 08 '26 22:08

Arkh


1 Answers

In other what is the proper way of handling parenting chain for QMenu and sharing QMenu?

You cannot share a QMenu across multiple places -- each QMenu can only exist in one place at a time. You should create separate QMenus: One for your menu bar and one for your context menu.

A simple way is to put your menu-generating code in a for-loop, to create multiple identical menus.

May I ask why you want to reuse your QMenu?

I can test that this is linked to the parenting chain : thisMenu is not a child of contextMenu

Yes, that is described in the documentation. When you add one QMenu to another, the parent doesn't change: http://qt-project.org/doc/qt-5/QMenu.html#addMenu

if I create it a child of contextMenu, everything is fine.

The position of a widget is always painted in a position relative to its parent. (Remember: A QMenu is a QWidget)

like image 69
JKSH Avatar answered Aug 10 '26 11:08

JKSH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!