Qt/QML: 尝试使用 TextEdit 创建日志文件视图,结果非常慢

Qt/QML: Trying to create a log file view with TextEdit, result is really slow

我正在开发 Android 应用程序。我需要显示一个类似于日志类型的控制台,它将由 C++ 后端写入。我试过结合 TextEdit 和 ScrollView 来做这个,但结果真的很慢。只要我的日志超过 ~50 行,添加几行就会减慢(锁定)界面几秒钟。

整理源代码,这是日志查看部分:

property int logMaxLines: 50

ScrollView {
    id: logScrollView
    anchors.fill: parent
    clip: true
    ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
    TextEdit {
        id: logTextEdit
        anchors.fill: parent
        readOnly: true
        color: "darkgreen"
        property int linesTrimmed: 0
    }
}

Connections{
    target: gate
    onNewMessageLineAdded :
    {
        logTextEdit.append(gate.newMessageLine)
        if (logTextEdit.lineCount > logMaxLines) {
            while (logTextEdit.lineCount >= logMaxLines) {
                logTextEdit.text = logTextEdit.text.slice(logTextEdit.text.indexOf('\n')+2)
                logTextEdit.linesTrimmed++
            }
            logTextEdit.insert(0, "[... trimmed " + logTextEdit.linesTrimmed + " lines ...]\n")
        }
    }
}

我选择了 ScrollView,因为我想要垂直滚动条。当 C++ 代码发出 newMessageLineAdded 信号时,它一次添加一行。这来自 class,其中包括 Q_PROPERTY,用于传递新行内容:

Q_PROPERTY(QString newMessageLine READ newMessageLine NOTIFY newMessageLineAdded)

信号声明为:

void newMessageLineAdded();

当日志变得太长时,我已将 java 的一小部分添加到 trim 日志中,因为即使 trimming 代码不存在,问题仍然存在。

我在这里做的事情很笨拙吗?我是否应该使用另一种类型的对象来替换 TextEdit,因为它根本不用于编辑文本,而仅用作显示? 谢谢

我推荐你使用ListView instead of TextEdit. And use QStringListModel as model declared in C++ code and added to QML as context property. Read Embedding C++ Objects into QML with Context Properties。为了获得更好的性能,建议在 C++ 代码中包含大部分逻辑。