Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QTreeView get right-clicked item



  • Using QTreeView paired with QStandardItemModel and trying to get contenxt-menu working when a user-right clicks on an item and then display custom menu for each item.

    In mainwindow.cpp code, I connected customContextMenuRequested signal with my slot - which is getting invoked properly. The issue I'm having is getting the item that the user right-clicked.

            auto pCurrModel = (QStandardItemModel*)pProxyModel->sourceModel();
    	auto index = ui.treeView->indexAt(pos);
    	auto item = pCurrModel->itemFromIndex(index);
    

    The code above is from OnCustomContextMenuRequested slot. I'm getting a valid index from indexAt() But itemFromIndex() always returns nullptr?


  • Lifetime Qt Champion

    Hi
    Do you have a proxymodel or anything like that active also ?
    So code should be something like

    QStandardItem *item = mymodel->itemFromIndex( mysortproxy ->mapToSource(index) );
    

    update:
    Ah. pProxyModel->sourceModel(); suggest you do have :)
    Amazing what eyes sometimes skips...


  • Lifetime Qt Champion

    Hi
    Do you have a proxymodel or anything like that active also ?
    So code should be something like

    QStandardItem *item = mymodel->itemFromIndex( mysortproxy ->mapToSource(index) );
    

    update:
    Ah. pProxyModel->sourceModel(); suggest you do have :)
    Amazing what eyes sometimes skips...



  • @mrjj
    Just to say: what a coincidence! I am literally sitting down right now to add right-click onto items in a QTreeView using a proxy model!


  • Lifetime Qt Champion

    @JonB

    Heh.
    That is perfect timing and also made me read his code properly
    and i do think he has a proxy :)



  • @mrjj Yes, I am using Proxy model and thanks for the quick solution. It works!


Log in to reply