问题
I have an RSS feed with escaped HTML characters that I want to display in a Text component where I trim the excess content with elide: Text.ElideRight
and wrapMode: text.WordWrap
.
While this works very well for plain text, when I use textFormat: Text.RichText
the trimming does not work.
How can I make the trimming to work or, if this is impossible, encode the HTML easily prior to binding it to the text component?
回答1:
Indeed Text
doesn't support elide
for Text.RichText
.
There is a bug open on the Qt bug tracker, and after the first reply there is a possible solution, that I copy and paste here for an easy read:
TextEdit {
property string htmlText: "<b>"+workingText.text+"</b>"
text: htmlText
width: parent.width
onHtmlTextChanged: {elide();}
onWidthChanged: elide();//Yes, this will be slow for dynamic resizing and should probably be turned off during animations
function elide(){//Also, width has to be set, just like elide, or it screws up
text = realText;
var end = richText.positionAt(width - 28,0);//28 is width of ellipsis
if(end != realText.length - 7)//Note that the tags need to be taken care of specially.
text = realText.substr(0,end + 3) + '…' + '</b>';//3 is + <b>
}
font.pixelSize: 22
}
回答2:
I figured a simple workaround which works quite well in my case, where the width and height of the Text component are fixed, i.e. trimming the string manually. The end result depends a bit on how monospace your font is.
text: {
var name = "my very very long text string with HTML markup that goes on forever and ever and ever"
var text = name.substring(0,45)
if (name.length > 45) text += "..."
return text
}
来源:https://stackoverflow.com/questions/29921385/qml-use-texts-elide-property-with-textformat-richtext