Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML: superscript/subscript text

The problem is that QML totally ignores <sub> and <sup> html tags, that are actually mentioned in official Supported HTML Subset.
So the following code will display regular "xy" insted of "xy":

Text {
text: "x<sup>y</sup>"
}

Is there any another possible way to display subscript/superscript text?

UPD: this is a known bug for newest Qt Quick versions since Qt 5.0. You can help getting the bug fixed by voting for it here or here

like image 726
Bolein95 Avatar asked Dec 04 '22 06:12

Bolein95


2 Answers

I added textFormat: Text.RichText to get sub and sup to work properly:

Text {
    textFormat: Text.RichText
    text: "Normal<sub> Subscript</sub> <sup>Superscript</<sup>"
}
like image 111
moose Avatar answered Jan 15 '23 02:01

moose


Since this seems to be a Qt bug, you need a workaround if you want this to work now. As it happens, I was inspired to play with Canvas element (which is basically HTML5 canvas element, some documentation for example here). By taking the hard-coded values from QML properties, the snippet below could be easily expanded to a simple configurable special-purpose text element.

Canvas {
    anchors.fill: parent
    onPaint: {
        var basetext = 'x';
        var suptext = 'y';

        var ctx = this.getContext("2d");

        ctx.strokeStyle = "blue";
        ctx.fillStyle = "red";

        ctx.font = 'bold 20px serif';
        ctx.strokeText(basetext, 20, 30);

        var metrics = ctx.measureText(basetext);
        console.debug('basetext width:', metrics.width);

        ctx.font = 'italic 12px serif';
        ctx.fillText(suptext, 20+metrics.width, 20);
    }
}

Note: when playing around with code like this, it pays to pay attention to the console output, for stuff like warnings about invalid font.

like image 36
hyde Avatar answered Jan 15 '23 03:01

hyde