首页 > 解决方案 > 有没有办法用QML TextEdit 的 selectedText 属性中的替代文本替换标签

问题描述

我有一个TextEdit用于显示短信的组件。解析消息时,我使用我的组件上的<img>标签和设置将常用的表情符号快捷方式替换为表情符号。当有人复制包含表情符号的消息时,属性插入一个 OBJECT REPLACEMENT CHARACTER 0xFFFC 而不是选定的标签。textFormat: TextEdit.RichTextTextEditselectedTextTextEdit<img>

例子:

import QtQuick 2.9
import QtQuick.Controls 2.2


Item {
    id: root
    width: 500
    height: 500

    TextEdit {
        id: myTextEdit

        anchors.centerIn: parent
        text: "Test <img src=\"app.icns\"></img> image"
        textFormat: TextEdit.RichText
        readOnly: true
        selectByMouse: true

        onSelectedTextChanged: {
            console.log(selectedText);
        }
    }
}

当您选择其中的所有内容时,myTextEdit它会打印“Test  image”。有没有办法指定一些其他的替换方式<img>selectedText所以我可以选择一些替代文本而不是 0xFFFC。

标签: qtqmlqtquickcontrols2

解决方案


您可以使用selectionStartandselectionEnd来获取该范围内的实际文本,text而不是依赖selectedText.

就像是:

    console.log(text.slice(selectionStart, selectionEnd));

推荐阅读