Viku
Viku

Reputation: 2973

Adding contextmenu for QTreeWidgetItem

Inside constructor

connect(ui.UserSpecificMaterial_treeWidget, SIGNAL(customContextMenuRequested(const QPoint &)),this, SLOT(ContMenu(const QPoint &)));

Inside slot

void MyContMenu::ContMenu(const QPoint &pos)
{
 QTreeWidgetItem *item = ui.UserSpecificMaterial_treeWidget->itemAt(pos);
     if (!item)
         return;
    QMenu *menu = new QMenu(ui.UserSpecificMaterial_treeWidget);
        myAction = menu->addAction("Remove");
    myAction->setIcon(QIcon(QString::fromUtf8("Resources/Remove.png")));
    myAction->setShortcut(tr("Ctrl+D"));
    myAction->setStatusTip(tr("Remove the respective material from the User DB"));
    menu->exec(ui.UserSpecificMaterial_treeWidget->viewport()->mapToGlobal(pos));
          /---code to remove the item ./ }

In the above code whenever i right click on the QTreeWidgetItem it will show me the contextmenu having a single menuitem named Remove . What i want is whenever the user click on that remove menuitem at that time only it should remove that QTreeWidgetItem from the qtreewidget . but in the above code after rigtclick even if i click on any part of the UI it removes the respective QTreeWidgetItem from the treewidget , which i want to avoid .

Thankss in advance .

Upvotes: 0

Views: 1330

Answers (1)

c_k
c_k

Reputation: 1766

You have to check the return value from QMenu::exec(...).

Like this:

QAction* item = myMenu.exec(QCursor::pos());

Now you can check against for instance the QAction::text() method to see if Remove was actually clicked or not.

Upvotes: 3

Related Questions