Context Menu on QTreeWidget Items

Hi,

How do we create context menu’s for QTreeWidget Item. This popup menu should be visible only on the selected item.

The Tree Creation

*QTreeWidgetItem *item;
QFont font;
font.setBold(true);
font.setWeight(75);

item = new QTreeWidgetItem;
item->setText(0,"ITEMS");
item->setFont(0,font);

treeMain = new QTreeWidget;
treeMain->setHeaderItem(item);
treeMain->setSortingEnabled(true);
treeMain->sortByColumn(1,Qt::AscendingOrder);

item = new QTreeWidgetItem;
item->setText(0,"New");
treeMain->addTopLevelItem(item);
treeMain->setContextMenuPolicy(Qt::CustomContextMenu);
txtMain = new QTextBrowser;

boxMain = new QHBoxLayout;
boxMain->addWidget(treeMain);
boxMain->addWidget(txtMain);
boxMain->setStretchFactor(treeMain,1);
boxMain->setStretchFactor(txtMain,3);

centralWidget = new QWidget;
centralWidget->setLayout(boxMain);

this->setCentralWidget(centralWidget);

The Actions for the menu
*nodeMenu = new QMenu(treeMain);

insertNodeChild  = new QAction("Insert Child",nodeMenu);
insertNodeAfter  = new QAction("Insert Node After",nodeMenu);
insertNodeBefore = new QAction("Insert Node Before",nodeMenu);
deleteNode       = new QAction("Delete Node",nodeMenu);

nodeMenu->addAction(insertNodeChild);
nodeMenu->addAction(insertNodeAfter);
nodeMenu->addAction(insertNodeBefore);
nodeMenu->addAction(deleteNode);

How do I show the above actions in context menu for the tree item.
Please help me.

Thanks
Ganesh

Hi,

just set the context menu policy for the tree widget should do the trick. Then simply add the actions to the tree widget and they should be shown on right click.

For example:
*treeMain = new QTreeWidget;
treeMain->setContextMenuPolicy(Qt::ActionsContextMenu);

insertNodeChild = new QAction(“Insert Child”,nodeMenu);
treeMain->addAction(insertNodeChild);
*

Hope this helps

Hi Monex,

It works like charm.

Thanks
Ganesh

Hi,

Thank It work for me too but how to add slots for those actions ?