qtqmlqtextdocument

Can I use custom tags in Qt's QTextDocument?


I know that the Qt QTextDocument and the Qt QML Text type support a set of supported tags and supported CSS properties, forming a subset of HTML 4.

But is there any way to extend which tags I can use? For example when I'd want to render custom XML without first converting it to HTML (via Qt's XSL-T or other means). Or similarly, when I'd want to visually implement an element not yet supported by Qt's subset of HTML 4.


Solution

  • Indeed you can, though this is undocumented behavior and you should be aware of the risks (such as, this behavior could vanish in future versions of Qt). Basically you can just use whatever tag names you want and style them with the available CSS properties. I tested this with Qt 5.12.

    Demonstration with a document that you can try in QML Text (and by extension also QTextDocument, though I did not test that explicitly):

    <html>
        <head>
            <style>test-tag { font-weight: bold; }</style>
        </head>
        <body>
            <test-tag>Hello Test Tag!</test-tag>
        </body>
    </html>
    

    Pretty cool 🙂

    If you use tag names containing a dash character (-), then your custom tags are valid in HTML5, as that makes them compliant with the Custom Elements Specification (details).