Home About

SVG text incorrectly overlapping



If I run this minimal reproducible example:

#include <QApplication>
#include <QLabel>
#include <QSvgRenderer>
#include <QPainter>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QSvgRenderer svgRenderer(QByteArray(R"(
<svg xmlns="http://www.w3.org/2000/svg">
    <text x="50" y="50" dx="7" dy="17">297</text>
    <text x="50" y="50" dx="7" dy="-3">TEXT</text>
</svg>
)"));
    QLabel label;
    label.setFixedSize(100, 100);
    QPixmap pixmap(100, 100);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    svgRenderer.render(&painter, QRectF(0, 0, 100, 100));

    label.setPixmap(pixmap);

    label.show();

    return app.exec();
}

I get this result:

As you can see, the two texts overlap each other.
Now, if I open this SVG file in a browser:

<svg xmlns="http://www.w3.org/2000/svg">
    <text x="50" y="50" dx="7" dy="17">297</text>
    <text x="50" y="50" dx="7" dy="-3">TEXT</text>
</svg>

I get two strings that that doe not overlap each other:

And this is how it looks on your browser (I added a red border):

    297
    TEXT



But why?

musicamante said:
Qt only fully supports SVG 1.2 Tiny, for which the text element does not support dx or dy. Since 6.7 the support has been partially extended to some features of SVG 1.1 (but the docs don't mention adding those attributes for text, I cannot test it right now). You should be very careful when working with text alignments, though, as they always depend on the installed fonts.
I'm not that familiar with SVG, so all I can suggest is to find a way to force positioning the bits of text. Fragile? Yes. Not that good of a solution if you cannot manipulate the SVGs or it's not manageable to do so? Yes.

This blog just serves as a big sign to what the actual problem is, I stripped away the noise (hopefully not too much) so that you can focus on the core issue.

This was inspired by this Stack Overflow question: SVG text is incorrectly overlapping