带有CheckDelegate项的ListView在滚动时不保留选中的复选框

2024-10-05 14:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

Holla,所以我有一个简单的脚本,在一个GUI中显示100个元素,每个元素都有一个复选框,我可以选中这些框,它们会保持选中状态一段时间,但是如果我向上或向下滚动直到它们消失,它们将被重置(有时只检查第一个元素)。 现在我知道在ListView中,元素一旦进入视图就会显示出来,我已经尝试了多种方法,比如增加ListView的高度、ContentHeight,但是没有任何效果。 此问题与RadioDelegate相同 主.py文件:

from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtCore import QObject, QUrl,QTimer
import sys
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine('main.qml')
sys.exit(app.exec_())

在主.qml公司名称:

^{pr2}$

视频说明:Click Me

我做错什么了? Update:经过进一步的研究,我发现我必须将选中的项存储在一个数组中,因为我对python/qml非常陌生,我该怎么做呢? 谢谢您。在


Tags: fromimport脚本app元素状态sysgui
1条回答
网友
1楼 · 发布于 2024-10-05 14:27:50

如果对问题进行了分析,可以观察到,如果您稍微移动列表并返回到初始位置,则更改将正确地保留值,并且当您像您的情况一样移动大量时,更改将丢失。

为什么会这样?

造成这种现象的原因是为了提高效率,ListView有一个名为^{}的属性,它可以保持某些项的持久性。

然后,解决方案是将更改保存在其他元素中,该元素将数据持久存储为^{}

ApplicationWindow {
    visible: true
    width: 400
    height: 550
    title: qsTr("Ttile")

    ListModel {
        id: checkmodel
        Component.onCompleted: {
            for(var i = 0; i < 100; i++){
                checkmodel.append({"name": i, "value": false})
            }
        }

    }
    ColumnLayout {
        anchors.fill: parent

        ListView {
            id: listView
            objectName : "lvob"
            model: checkmodel
            delegate: CheckDelegate {
                text: name
                checked: value
                onCheckStateChanged: checkmodel.setProperty(index ,"value", checked)
            }
            Layout.fillWidth: true
            Layout.fillHeight: true
            ScrollBar.vertical: ScrollBar {}
        }
    }
}

其他可能的容器可能正在使用其他^{}s:

model : model

This property holds the model providing data for the list.

The model provides the set of data that is used to create the items in the view. Models can be created directly in QML using ListModel, XmlListModel or VisualItemModel, or provided by C++ model classes. If a C++ model class is used, it must be a subclass of QAbstractItemModel or a simple list.

See also Data Models.

相关问题 更多 >