如何在QTreeWidget中选择一个项目?

时间:2021-01-26 15:05:39

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.

我正在尝试创建一个功能,如果没有选择任何项目,将选择QTreeView中的最后一项。我不知道如何选择程序中的项目。到目前为止,我已经尝试过这个,但它不起作用。

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.

treeWidget是一个QTreeWidget对象,selectedItemList是其中所选项的列表。我将非常感谢所有的帮助。

2 个解决方案

#1


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

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

#1


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

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