Łukasz Przeniosło
Łukasz Przeniosło

Reputation: 2949

How to select an item in QTreeWidget?

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.

Upvotes: 3

Views: 13468

Answers (2)

Lahiru Chandima
Lahiru Chandima

Reputation: 24068

if (treeWidget->selectedItems().size() == 0 && treeWidget->topLevelItemCount())
{
    treeWidget->topLevelItem(treeWidget->topLevelItemCount() - 1)->setSelected(true);
}

Upvotes: 6

Bowdzone
Bowdzone

Reputation: 3854

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);
}

Upvotes: 3

Related Questions