In Qt + VS2005, using the slot function customContextMenuRequested (QPointpos) to achieve Treewidget right menu bar.
1, in the editing interface ui, right QTreeWidget -> Connect Signal -> select customContextMenuRequested (QPoint), add slot function.
In the property, the property will be set to contextMenuPolicy: CustomContextMenu, can not forget this step, otherwise no reaction right.
2, add node Treewidget, by setData () to impart a different key for each node.
QTreeWidgetItem *root; root = new QTreeWidgetItem(ui->treeWidget, QStringList(QString("Connection"))); QVariant var0 (0); root->setData(0,Qt::UserRole,var0);
3, used in the slot function itemAt () function to get the current node is clicked, then add different menus for different nodes.
void MainWindow::on_treeWidget_customContextMenuRequested(QPoint pos) { QTreeWidgetItem * curItem = ui-> treeWidget-> itemAt (pos); // Get the current node is clicked if (curItem == NULL) return; // this case is not the right position treeItem range, i.e., right-click on a blank position QVariant var = curItem->data(0,Qt::UserRole); if (0 == var) // data (...) returns the data has been used in establishing setdata node before () set { QMenu * popMenu = new QMenu (this); // define a right pop-up menu popMenu-> addAction (ui-> action_newDB); // add to the menu QAction the action in front of a designer defines popMenu->addAction(ui->action_openDB); popMenu->addAction(ui->action_delDB); popMenu-> exec (QCursor :: pos ()); // pop-up context menu, the menu location for the cursor position } else { QMenu * popMenu = new QMenu (this); // define a right pop-up menu popMenu-> addAction (ui-> action_newTable); // add to the menu QAction the action in front of a designer defines popMenu->addAction(ui->action_openTable); popMenu->addAction(ui->action_designTable); popMenu-> exec (QCursor :: pos ()); // pop-up context menu, the menu location for the cursor position } }
Reference: http: //blog.csdn.net/moxiaomomo/article/details/6542683