tags:

views:

648

answers:

2

I want to add a submenu in my context menu which is created like this:

self.widget_alignment.setContextMenuPolicy(Qt.ActionsContextMenu)

where widget_alignment is QTableWidget.

I created a new QMenu instance:

exchange_bases_menu = QMenu(self.widget_alignment)

added some actions, and I found a method QAction QMenu.addMenu (self, QMenu menu)

but I don't see any reference to the default context menu for self.widget_alignment. Additionally, this code:

self.widget_alignment.addMenu(exchange_bases_menu)

gave me: QTableWidget object has no attribute addMenu.

How can I add my submenu to the default context menu?

A: 

What about using QMenu's popup() in MouseReleaseEvent?

if (pEvent->button() == Qt::RightButton)
{
    QMenu menu;
    menu.addAction(action1);
    menu.addAction(action2);
    menu.popup(pEvent->globalPos(),action1);
}
Vicken Simonian
+1  A: 

According to the documentation, when a QWidget is set to have the actions context menu type, the widget will construct a context menu based on the list of actions set for the widget. To modify the list of actions, you can call addAction, insertAction, or removeAction. So I would expect you could do something like this (in C++):

QAction *act_p = new QAction( "Has Submenu", widget_alignment );
QMenu *submenu_p = new QMenu( act_p );
// Add items to the submenu
act_p->setMenu( submenu_p );
widget_alignment->addAction( act_p );

Without trying it myself, I would expect this to add a "Has Submenu" option to the bottom of the context menu that is generated for the widget, with the submenu you created as the submenu shown.

Caleb Huitt - cjhuitt
Thanks cjhuitt!That's what works for me (in Python):act_p = QAction( "Has Submenu", self.widget_alignment)submenu_p = QMenu(self.widget_alignment)# Add items to the submenusa = QAction("Submenu action", submenu_p)submenu_p.addAction(sa)act_p.setMenu(submenu_p)self.widget_alignment.addAction(act_p)
piobyz