获取另一个组件中的组件属性

时间:2017-10-23 00:06:08

标签: qt qml

我正在用QML实现测试系统。按下部分(例如问题)中的某些答案后,answered上的属性true应该更改,因此我将无法再按此部分中的答案。我在answerDelegate MouseArea点击处理程序中检查了该内容。但我无法访问answered属性。

任何想法如何连接它们?

Rectangle {
    id: root
    anchors.fill: parent

    property ListModel testModel: ListModel {}
    property int totalAnswers: 0
    property int questionsCount: 0   

    function setTestModel(tests){
        testModel.clear()
        testModel.append(tests)
    }

    ScrollView {
        id: testsScroll
        anchors.fill: parent

        ListView {
            id: testsView
            anchors.fill: parent
            model: testModel

            delegate: answersDelegate

            section.property: "question"
            section.delegate: questionDelegate
        }
    }

    Component {
        id: questionDelegate

        Rectangle{
            id: questionItem
            // the property I need to get access
            property bool answered: false
            width: parent.width
            height: 40

            Text {
                anchors.left: parent.left
                text: section
            }

            Component.onCompleted: {
                questionsCount += 1
            }
        }
    }

    Component {
        id: answersDelegate
        Item {
            id: oneItem
            width: parent.width
            height: 30

            Rectangle {
                id: answerRectangle

                Text {
                    anchors.left: parent.left
                    text: content
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        // here I check it
                        root.answerClicked()
                        if (!questionDelegate.answered) {
                            questionDelegate.answered = true
                            answerRectangle.color = correct == true ? "#00ff00": "#ff0000"
                            if (correct) total += 1
                        }
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您无法访问组件属性Component不是实例。它更像是一个工厂,设置为生成具有相同配置的任意数量的实例。

如果Component作为ListView的委托,则ListView会创建多个实例,模型中每个条目一个,只要它适合视图端口。现在,您将拥有该组件的多个实例,并且每个实例可能具有不同的属性值。您希望阅读哪一个?

因此,您无法使用id内的Components来访问其内部。相反,您需要访问您在某处创建的具体实例,并阅读此实例的属性。

此外,您应该注意,不建议在委托中设置委托的状态,因为它们是动态创建和销毁的。如果您在委托中设置answered - 标志(问题或answerDelegate)然后滚动,则答案可能会离开视口,委托会被销毁,信息也会丢失。

而是回写模型中的更改,它们更具持久性。

相关问题