QML ListView计数为零,并且只有一些行可见

QML ListView count is zero and only some rows are visible

本文关键字:ListView QML      更新时间:2023-10-16

我创建了一个基于QAbstractListModel的ListView模型,类似于本例。问题是我的ListView并没有显示所有的行,而是只显示那些初始可见的行。所以当我向下滚动(或轻弹)时,只有黑色的空间。ListView的count==0,但它应该有count==10,因为我添加了10个元素。

我的类包含更新模型rowCount 的必要方法

// needed as implementation of virtual method
int rowCount(const QModelIndex & parent) const {
return standings.size();
}
int rowCount() {
return standings.size();
}
void addStanding(const Standing &st) {
beginInsertRows(QModelIndex(), rowCount(), rowCount());
qDebug() << "row cnt: " << rowCount();
standings << st;
endInsertRows();
}

我还更新了ListView模型

rootContext = (QDeclarativeContext*)(viewer->rootContext());
rootContext->setContextProperty("myModel", &sm);

QML代码

ListView {
id: raceList
objectName: "standingList"
y: header.height
width: parent.width
height: parent.height - header.height
clip: true
model: myModel
delegate: rowComp
}
Component {
id: rowComp
SessionRowDelegate { }
}

我还想提一下,这对于静态模型来说是很好的。如何使ListView始终显示所有项目,而不仅仅是在用户可见的情况下

SessionRowDelegate

Rectangle {
id: rowbg
width: parent.width
height: 34 * (1 + (parent.width - 360) * 0.002)
// contains other elements with height not exceeding rowbg's height
// ...
}

现在有点晚了(4年了!),但在被困了几天后,我发现了与这个问题有关的一些事情!这个问题主要是基于ListView处理模型的奇怪方式。

在我自己的模型中重写rowCount方法之后,我遇到了您提到的确切问题。有趣的是,他们从来没有被打过电话。ListView实际上从未调用以获取rowCount,而是查询cacheBuffer大小中的数量(在我的系统中默认为512),这就是为什么它不会注意到项目是否大于cacheBuffer或它使用的默认大小,它只会在滚动到最后时注意到这一点。


虽然这会揭示其他人的一些问题,但它不是解决你问题的方法。在您的情况下,如果项目没有那么多,我建议调整ListView cacheBuffer的大小,并根据需要增加它。请记住,如果你的元素数量众多,可能会对性能造成巨大影响。

ListView只渲染当前可见的元素以及一些预先渲染的元素,以便在滚动时显示。由于性能原因,默认实现不会呈现所有这些。对列表大小的任何引用都应该引用模型对象,而不是ListView本身。