To add a right-click menu bar in a form, for example, add a menu bar in QTreeWidget,
The slot function customContextMenuRequested (QPoint pos) can be used ).
If it is in Qt Creator, right-click QTreeWidget --> go to slot --
--> Select customContextMenuRequested (QPoint pos ).
Then, you can implement the specific menu bar in the newly created customContextMenuRequested (QPoint pos) function.
In order to determine the right-click position, that is, the points are different item nodes, different right-click menus are displayed. We can use the itemAt () function in the API.
To assign different key values to each node, you can use setData.
I added the implementation code of the right-click menu in TreeWidget:
Code implementation for creating the TreeWidget root node:
QTreeWidgetItem * root;
Root = new QTreeWidgetItem (ui-> treeWidget, QStringList (QString ("Connection ")));
QVariant var0 (0 );
Root-> setData (0, Qt: UserRole, var0 );
Void MainWindow: on_treeWidget_customContextMenuRequested (QPoint pos)
{
QTreeWidgetItem * curItem = ui-> treeWidget-> itemAt (pos); // obtain the currently clicked Node
If (curItem = NULL) return; // In this case, the right-click position is not within the treeItem range, that is, right-click the blank position
If (0 = curItem-> data (0, Qt: UserRole) // The data returned by data (...) has been set with setdata () when a node was created.
{
QMenu * popMenu = new QMenu (this); // right-click to define a menu
PopMenu-> addAction (ui-> action_newDB); // Add QAction to the menu. This action is defined by the designer.
PopMenu-> addAction (ui-> action_openDB );
PopMenu-> addAction (ui-> action_delDB );
PopMenu-> exec (QCursor: pos (); // right-click the menu and select the cursor position.
}
Else
{
QMenu * popMenu = new QMenu (this); // right-click to define a menu
PopMenu-> addAction (ui-> action_newTable); // Add QAction to the menu. This action is defined by the designer in the previous step.
PopMenu-> addAction (ui-> action_openTable );
PopMenu-> addAction (ui-> action_designTable );
PopMenu-> exec (QCursor: pos (); // right-click the menu and select the cursor position.
}
}
Note:
Add the following to the MainWindow constructor:
Ui-> treeWidget-> setContextMenuPolicy (Qt: CustomContextMenu );
Otherwise, no right-click is displayed !!
Laokaddk BLOG