为什么Qt列表窗格指示存在选择,即使用户未选择项目且没有项目显示为已选择?

为什么Qt列表窗格指示存在选择,即使用户未选择项目且没有项目显示为已选择?,qt,Qt,我不明白为什么我的QListView返回一个选择,即使用户没有选择一个项目,也没有一个项目显示为选中,并且在显示之前在窗格上调用clearSelection() 以下是创建列表项的相关代码: class WidgetInstanceIdentifier {...} // This class is properly registered with Qt listpane = new QListView(...); QStandardItemModel * model = new QStanda

我不明白为什么我的
QListView
返回一个选择,即使用户没有选择一个项目,也没有一个项目显示为选中,并且在显示之前在窗格上调用
clearSelection()

以下是创建列表项的相关代码:

class WidgetInstanceIdentifier {...} // This class is properly registered with Qt

listpane = new QListView(...);
QStandardItemModel * model = new QStandardItemModel(listpane);

int index = 0;
std::for_each(vg_list.cbegin(), vg_list.cend(), [&](WidgetInstanceIdentifier const & vg)
{

    QStandardItem * item = new QStandardItem();
    std::string text = "...";
    item->setText(text.c_str());
    item->setEditable(false);
    item->setCheckable(false);
    QVariant v;
    v.setValue(vg);
    item->setData(v);
    model->setItem( index, item );

    ++index;

});

model->sort(0);

listpane->setModel(model);

listpane->clearSelection();
下面是一个屏幕截图,显示了我单击“确定”时的对话框。请注意,列表窗格中的两个项目均未选中:

。。。以下是测试选择的相关代码:

QItemSelectionModel * listpane_selectionModel = listpane->selectionModel();
QModelIndex selectedIndex = listpane_selectionModel->currentIndex();
if (!selectedIndex.isValid())
{
    // This block of code is not hit!!!!!!
    // I expect it would be hit
}

QVariant vg_variant = listpaneModel->item(selectedIndex.row())->data();

// The following variable is properly set to correct data representing
// the first item in the list
vg_to_use = vg_variant.value<WidgetInstanceIdentifier>();
QItemSelectionModel*listpane_selectionModel=listpane->selectionModel();
QModelIndex selectedIndex=listpane_selectionModel->currentIndex();
如果(!selectedIndex.isValid())
{
//这段代码没有命中!!!!!!
//我想它会被击中
}
QVariant vg_variant=listpaneModel->item(selectedIndex.row())->data();
//以下变量已正确设置为正确的数据
//列表中的第一项
vg_to_use=vg_variant.value();
正如代码中所指出的,我希望在“无选择”的情况下命中的代码块(!selectedIndex.isValid()){…}块没有命中。相反,将返回列表中的第一项,就好像它已被选中一样。这是不可取的!用户无法知道到底选择了哪个项目


我误解了什么?为什么Qt似乎报告存在有效的选择,即使列表中没有选择任何项目?检查是否真的没有选择项目的正确方法是什么?

我认为所选项目和当前项目不是一回事。虽然,在某些情况下也可以选择当前项,但这并不一定。通常是视图中由虚线轮廓指示的当前项。因此,如果要检查选择项计数,请使用
QItemSelectionModel::selectedIndex()
函数进行检查,即:

QModelIndexList selected = listpane_selectionModel->selectedIndexes();
if (!selected.isEmpty()) {
    // do something
}

你爱上了一个名字。你用一种方式命名,但它不是你所命名的。也就是说,
listpane\u selectionModel->currentIndex()
与选择无关。它只是当前活动的索引,但不一定是选中的。要迭代选定索引的列表,请执行:
foreach(QModelIndex idx,listpane_selectionMode->selectedindex()){……}
我感谢您的评论!谢谢