QTreeWidget right click menu

后端 未结 4 1752
离开以前
离开以前 2021-02-03 11:31

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 a

4条回答
  •  生来不讨喜
    2021-02-03 12:17

    For those who prefer to use designer more, here is another way to do it:

    1) Set context menu policy to custom context menu

    Either by code:

    ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    

    or using graphical designer, click on the tree widget and set it using Property Editor:

    2) Create Handler function

    In designer, right click on the treeWidget and select "Go to Slot..." option. A window similar to this will appear:

    Click on the "CustomContextMenuRequested(QPoint)" option. Handler function will be defined, declared, and it will be connected automatically.

    void MainWindow::on_treeWidget_customContextMenuRequested(const QPoint &pos)
    {
      // this function will be called on right click
    }
    

    This step can also be done by defining and connecting the slot function yourself.

    3) Create the options on the context menu.

    Go to action editor tab (Usually docked at the bottom of designer). Add actions you want to have on context menu by clicking new button on top left. You will encounter such an interface :

    You can (optionally) have a tooltip or icon for the action, or make it checkable. You can crate a shortcut like Ctrl+C for a copy action.

    4) Create the menu and fire it

    void MainWindow::on_treeWidget_customContextMenuRequested(const QPoint &pos)
    {
        QMenu menu(this); // add menu items
        menu.addAction(ui->actionDelete);
        menu.addEdit(ui->actionDelete);
        ...
    
        ui->actionDelete->setData(QVariant(pos)); // if you will need the position data save it to the action
    
        menu.exec( ui->treeWidget->mapToGlobal(pos) );
    }
    

    5) Create handler functions for each action

    Like in step 2, either create slot function and connect it manually, or right-click on on an action, click the "Go to slots..." option and select triggered() slot.

    6) Lastly, apply your logic in the slot function

    void MainWindow::on_actionEdit_triggered()
    {
        QTreeWidgetItem *clickedItem = ui->treeWidget->itemAt(ui->actionDelete->data().toPoint());
    
        // your logic
    }
    

提交回复
热议问题