How to reset style for rich text in QML TextArea

Viewed 46

If I insert rich text in QML TextArea, it will preserve that style (text color, underline etc.) for further inputs. Is there a way to prevent that from happening?

Example:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    TextArea {
        id: textArea
        textFormat: Qt.RichText
        focus: true
        selectByMouse: true
        selectByKeyboard: true

        Keys.onPressed: {
            if (event.text === "@") {
                textArea.text += "<a href='mentioned://user'>@User</a>";
                event.accepted = true
            }
        }
    }
}

When I enter "@" character it will insert the <a> link instead, but when I continue typing other characters it will append them to the link, as if they are a part of it. How can I continue typing a new paragraph, without appending to the link ( tag)?

1 Answers

Adding a whitespace after the tag solves the problem :

Window {
width: 640;
height: 480;
visible: true;
title: qsTr("Code from @Meliodas on StackOverflow");

    TextArea {
        id: textArea;
        textFormat: Qt.RichText;
        focus: true;
        selectByMouse: true;
        selectByKeyboard: true;

        Keys.onPressed: (event) => {
            if (event.text === "@") {
                // HERE
                insert(cursorPosition, "<a href='mentioned://user'>@User</a> ");
                event.accepted = true;
            }
        }
    }
}

Note that I took the freedom of modifying other pieces of your code :

  • insert() instead of text += to avoid automatic newlines
  • explicitly defining event to silence a warning telling me implicit event parameters are deprecated
Related