1

Example Tree View:

1. a
1.1. b
1.1.1. c

I want to know how I can make my code recognize I right clicked whether a or b or c. I am able to create a TreeView, add a b c to it, and get the item at the position of the right click but I don't know how I can recognize the item so right clicks would create different context menus respecting the item clicked. I use standard item model (QStandardItemModel) and so far what I got is:

void MyWindow::make_tree_custom_menu(const QPoint& pos){
    QModelIndex index = treeView->indexAt(pos);
    int itemRow = index.row();
    int itemCol = index.column();
    QStandardItem* itemAtPos = model->item(itemRow, itemCol);
    itemAtPos->setText("meh");
}

I know that with QTreeWidgetItems you can do QTreeWidgetItem* newitem = new QTreeWidgetItem(name, itemtype); but as far as I could see in the docs, QStandardItem doesn't have such constructor. Also, I know that this exists, but it is unanswered. Therefore, I would like any help on possible methods to identify tree view items in such an application.

Community
  • 1
  • 1
Deniz
  • 509
  • 7
  • 26

1 Answers1

3

First of all, I suggest to use the QStandardItemModel::itemFromIndex(const QModelIndex & index) method to get the item in this case. The QStandardItemModel::item(int row, int column) method hasn't the parent parameter, so I think it returns only top level items (this method is good for lists or tables).

Then, when you get the item, you have exactly the pointer to the item you have created, so you have all you need to recognize it. If you want to set an attribute to the item to define a type (like QTreeWidgetItem itemType), you can use the QStandardItem::setData(const QVariant & value, int role) method (using e.g. the Qt::UserRole) when you create the item. Then you can get the item type using the QStandardItem::data(int role) method in your make_tree_custom_menu method.

See:

Fabio
  • 2,522
  • 1
  • 15
  • 25
  • Thank you for your informative comment. Everything looks clear and I can understand the idea here. However, even though I looked up and found the explanation below, I still don't quite get `const QVariant & value` and what it does. What do I use it for? `Sets the item's data for the given role to the specified value.` – Deniz Oct 09 '16 at 16:10
  • `QVariant` is a class that contains a value of a certain type, i.e. a sort of `union`. You can set the item type as an integer e.g with `item->setData(3, Qt::UserRole)` (you can replace the 3 value with your integer), and you can get the item type back with `item->data(Qt::UserRole).toInt()`. See [QVariant](http://doc.qt.io/qt-5/qvariant.html) – Fabio Oct 10 '16 at 06:21
  • Thank you again Fabio, everything is clear now. And I was able to implement this in my code. I have accepted your input as the answer. – Deniz Oct 10 '16 at 15:23