Reputation: 539
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 QTreeWidgetItem
s 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.
Upvotes: 1
Views: 1847
Reputation: 2602
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:
Upvotes: 3