How to select an item in QTreeWidget?

Łukasz Przeniosło picture Łukasz Przeniosło · May 13, 2015 · Viewed 8.8k times · Source

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.

Answer

Lahiru Chandima picture Lahiru Chandima · May 13, 2015
if (treeWidget->selectedItems().size() == 0 && treeWidget->topLevelItemCount())
{
    treeWidget->topLevelItem(treeWidget->topLevelItemCount() - 1)->setSelected(true);
}