TableView 中的 QML 和组合框

QML and comboBox inside TableView

我正在尝试设计一个在 TableView 中带有组合框的移动应用程序。

import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import QtQuick.Controls 1.2
import QtQuick.Window 2.0
import QtLocation 5.6
import QtPositioning 5.6
import QtQuick.Controls.Styles 1.2

ApplicationWindow {

    visible: true
    width: 640
    height: 480
    title: qsTr("Scroll")

    Component.onCompleted: {
        var i=0;
        for(;i<50;i++)
        {
            console.log("ApplicationWindow.onCompleted");

            var myBoject = {"text":"Banana"};
            idListModelForFlightToExport.append(myBoject);
        }

    }

    ListModel {
        id: idListModelForFlightToExport
    }

    Component  {
        id: checkBoxDelegate
        ComboBox {
            anchors.fill: parent;
            model: [ {"text":"Banana"}, {"text":"Apple"}, {"text":"Coconut"} ]
            textRole: "text";
            Component.onCompleted: {
                console.log("checkBoxDelegate.onCompleted");
            }
        }
    }

    TableView {
        id: idTableViewFlightsToExport

        sortIndicatorVisible: false

        model: idListModelForFlightToExport
        anchors.fill: parent
        TableViewColumn {
            id: isExportedColumn
            title: qsTr("Column")
            movable: false
            resizable: false
            delegate:checkBoxDelegate
        }
    }
}

但是当我更改组合框的值,然后向下滚动时,其他一些组合框会更改它们的值。

也就是说,如果我更改第一个组合并滚动,第一个组合的值将显示在另一个组合(似乎是随机选择的)上,并且第一个组合似乎已重置。如果我再次滚动,另一个组合更改值。

根据您使用的平台,有两个 po

#2 编辑

根据文档,这也可能是由于 TableView 在您的 Qt 版本中的标准行为

当项目被弹出时,它会移动到重用池,这是未使用项目的内部缓存。发生这种情况时,将发出 TableView::pooled 信号以通知该项目。同样,当项目从池中移回时,会发出 TableView::reused 信号。

任何来自模型的项目属性都会在项目被重复使用时更新。这包括索引、行和列,还包括任何模型角色。

注意:避免在委托中存储任何状态。如果这样做,请在收到 TableView::reused 信号时手动重置它。

在 TableView 上将 reuseItems 设置为 false 将解决此问题。

  TableView {
        id: idTableViewFlightsToExport
        reuseItems: false
        sortIndicatorVisible: false

        model: idListModelForFlightToExport
        anchors.fill: parent
        TableViewColumn {
          id: isExportedColumn
          title: qsTr("Column")
          movable: false
          resizable: false
          delegate:checkBoxDelegate
        }
    }

这是因为当您滚动时,TableView 会回收委托,而不是销毁离开视图的委托并重新创建将要显示的委托。这有助于提高性能。 在您的情况下,当代表被 TableView 洗牌时,您的状态将保持不变。

您不应将状态存储在委托中,而应将其存储在外部。

您可以在此处阅读更多相关信息:https://doc.qt.io/qt-5/qml-qtquick-tableview.html#reusing-items

我都,

感谢QT论坛的解答,解决了我的问题。这是我实施的解决方案:forum.qt.io/topic/110624/qml-and-combobox-inside-tableview

希望对您有所帮助。