How to control scrolling in TextArea
-
Hi
I want to use TextArea to display colored logs. I know that ListView is more efficient for this task, but for my use case TextArea fits (and I like the colored borders when focused). I wrapped the TextArea in a ScrollView, as the documentation suggests. I color and add text through a C++ class that implements QSyntaxHighlighting and inserts text through QTextCursor. So I don't use the TextArea append function or the +=. The problem is that every time I add new text, ScrollView scrolls to the end automatically, but I want to scroll to the top and look at the text that was added earlier, and when I'm done, I want to enable auto-scrolling again by just scrolling to the end or perhaps by using a button. I don't see a clear way to achieve this behavior. Many thanks in advance.the qml file code is
ScrollView { id: textAreaView Layout.fillHeight: true Layout.fillWidth: true wheelEnabled: true background: Rectangle { color: Material.background border.color: textAreaView.focus ? Material.accent : "#bdbebf" border.width: 2 } TextArea { id: textArea height: _root.height - textInput.height readOnly: true textFormat: TextEdit.PlainText width: _root.width wrapMode: Text.Wrap Component.onCompleted: { highlighter.onCompleted() } Connections { target: logger onDeviceLogReceived: function (msg) { highlighter.append(msg); } } HighlighterComponent { id: highlighter } }the c++ highlighter function
void Highlighter::append(const QString& text) { QTextCursor cursor(doc); cursor.movePosition(QTextCursor::End); static QRegularExpression regex("^\[\\d+:\\d+:\\d+\\.\\d+,\\d+\] <(dbg|inf|wrn|err)>"); QRegularExpressionMatch match = regex.match(text); if (match.hasMatch()) { QString tag = match.captured(1); MessageType type = getMessageType(tag); QTextCharFormat format = highlightingRules.value(type); cursor.insertText(match.captured(0), format); cursor.insertText(text.mid(match.capturedEnd()), defaultFormat); } else { cursor.insertText(text, defaultFormat); } cursor.insertText("\n", defaultFormat); }