首页 > 解决方案 > 如何以编程方式将文本附加到 QML TextArea?

问题描述

我正在尝试将日志数据一次传递到我的 QML 前端,并将其附加到 TextArea 的末尾。我考虑了几种方法。以下是最有希望的。我已经创建了一个 QAbstractListModel(在 Python 中)并将这个模型传递到一个转发器,它作为单个项目(rowCount = 1)到达,我使用该行附加到 TextArea

text: terminal_text.text + display

这可行,但每次更新文本时都会收到此警告。

file://.../TextArea.qml:728:9: QML QQuickTextEdit*: Binding loop detected for property "text"

中继器的代码见下文。

Repeater {
    model: TerminalFeed { }
    delegate: TextArea {
        id: terminal_text
        font.family: "Courier"
        width: parent.width
        height: parent.height
        readOnly: true
        selectByMouse: true
        wrapMode: TextEdit.NoWrap
        horizontalScrollBarPolicy: Qt.ScrollBarAsNeeded
        verticalScrollBarPolicy: Qt.ScrollBarAsNeeded
        text: terminal_text.text + display
    }
}

我怎样才能阻止这种情况发生?或者有没有人有更好的方法来达到同样的结果?

标签: qtqml

解决方案


从技术上讲,这确实是一个绑定循环,因为text它依赖于它自己的值。如果 QML 没有检测到它并破坏它,就会导致无限循环的更新。

您可以执行以下操作,而不是使用绑定:

Repeater {
    model: TerminalFeed { }
    delegate: TextArea {
        id: terminal_text
        font.family: "Courier"
        width: parent.width
        height: parent.height
        readOnly: true
        selectByMouse: true
        wrapMode: TextEdit.NoWrap
        horizontalScrollBarPolicy: Qt.ScrollBarAsNeeded
        verticalScrollBarPolicy: Qt.ScrollBarAsNeeded

        onDisplayChanged: {
            text = text + display;
        }
    }

}

使用原始的绑定方法,它会在任何时候尝试更新display text更改。使用这种方法,它只会在发生变化时尝试更新display——这正是你真正想要的。


推荐阅读