3

I am trying to make a functionality, that will select the last item in the QTreeView, if there are no items selected. I don't know how to select an item within the program. So far I have tried this, but it doesn't work.

if (selectedItemList.length() == 0) // no items selected
    {
        QItemSelectionModel *selection = new QItemSelectionModel(treeWidget->model());
        QModelIndex index = treeWidget->model()->index(treeWidget->model()->rowCount() - 1,
                                                       0, QModelIndex());
        selection->select(index, QItemSelectionModel::Select);
        treeWidget->setSelectionModel(selection);
        return;
    }

treeWidget is a QTreeWidget object and selectedItemList is the list of selected items in it. I would appreciate all help.

Hexaholic
  • 3,299
  • 7
  • 30
  • 39
Łukasz Przeniosło
  • 2,725
  • 5
  • 38
  • 74

2 Answers2

4
if (treeWidget->selectedItems().size() == 0 && treeWidget->topLevelItemCount())
{
    treeWidget->topLevelItem(treeWidget->topLevelItemCount() - 1)->setSelected(true);
}
Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179
  • The `setItemSelected` method is [on the deprecated list](http://doc.qt.io/qt-5/qtreewidget-obsolete.html) and it is therefore discouraged to use it. The selection can be done using the item directly – Bowdzone May 13 '15 at 11:20
2

You can interact with the selection directly using the items.

QList<QTreeWidgetItem*> selectedItemList = tree->selectedItems();
if (selectedItemList.length() == 0) // no items selected
{
    tree->topLevelItem(tree->topLevelItemCount()-1)->setSelected(true);
}
Bowdzone
  • 3,827
  • 11
  • 39
  • 52
  • The item is not being selected with this. I think QTreeView works like this that after the focus on an item is lost, the last item in the tree is being focused by default, but it is not selected visibly for sure. – Łukasz Przeniosło May 14 '15 at 06:00