QTreeWidget right click menu

ISTB picture ISTB · Jan 9, 2013 · Viewed 22.9k times · Source

I looked around and it seems that the problem is present not only for tree widget but also for other widgets. But in my case, I found a solution, although an incomplete one. I am adding actions to my tree widget, so that when you right click on it, a popup with these actions appears. However, when I add items to my tree widget and I right click on them, the same popup appears. What I would like to do is that when you right click on the tree widget, a tree widget popup menu appears and when you right click on items, another corresponding popup menu appears. Does anybody knows how to do this?

Answer

ndtc picture ndtc · Apr 7, 2015

First,config QTreeWidget to response(emit signal) right mouse click:

treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);

Second,connect the signal with your slot "MainWindow::prepareMenu":

connect(treeWidget,&QTreeWidget::customContextMenuRequested,this,&MainWindow::prepareMenu);

Third,create context menu in the slot:

void MainWindow::prepareMenu( const QPoint & pos )
{
QTreeWidget *tree = treeWid;

QTreeWidgetItem *nd = tree->itemAt( pos );

qDebug()<<pos<<nd->text(0);


QAction *newAct = new QAction(QIcon(":/Resource/warning32.ico"), tr("&New"), this);
newAct->setStatusTip(tr("new sth"));
connect(newAct, SIGNAL(triggered()), this, SLOT(newDev()));


QMenu menu(this);
menu.addAction(newAct);

QPoint pt(pos);
menu.exec( tree->mapToGlobal(pos) );
}