yonutix
yonutix

Reputation: 2439

QT context menu only over QTreeView Selection

I have a context menu which I want to appear only when is on top of an item from the QTreeView. When is on top of the blank space I want to do nothing. This is what I have until now

void MainTreeViewController::showContextMenu(const QPoint& pos)
{

    QPoint globalPos = mtreeView->mapToGlobal(pos);
    QMenu rightClickMenu;
    for(int i = 0; i < kCharModelRightClickOptionsCount; ++i){
        rightClickMenu.addAction("Menu option");
    }

    QAction* selectedItem = rightClickMenu.exec(globalPos);
    if (selectedItem){

    }
}

Thanks!

Upvotes: 1

Views: 400

Answers (1)

vahancho
vahancho

Reputation: 21220

First you need to find the model index under the cursor using QAbstractItemView::indexAt() function. Getting an invalid index will indicate that you click out of any tree view item. So, your code will look like:

void MainTreeViewController::showContextMenu(const QPoint& pos)
{
    // Do not show menu if clicked outside of tree view nodes.
    QModelIndex idx = mtreeView->indexAt(pos);
    if (!idx.isValid())
        return;

    QPoint globalPos = mtreeView->mapToGlobal(pos);
    QMenu rightClickMenu;
    for(int i = 0; i < kCharModelRightClickOptionsCount; ++i){
        rightClickMenu.addAction("Menu option");
    }

    QAction* selectedItem = rightClickMenu.exec(globalPos);
    if (selectedItem){

    }
}

Upvotes: 6

Related Questions