beep
beep

Reputation: 1245

Apply a custom stylesheet to QTextDocument

I want to apply some custom stylesheet to a QTextDocument using setDefaultStyleSheet function, however it get ignored.
According to this post i should add the style sheet after setting the html content, but this did not solve my problem.
My code:

QString *html = new QString();
*html = "<tr>" + name + "</tr>"
        "<tr>" + surname + "</tr>"
        "<tr>" + age + "</tr></table>";
QTextDocument doc;
doc.setHtml(*html);
doc.setDefaultStyleSheet("table { border: 1px solid black; }"); // This should apply the style sheet

Upvotes: 1

Views: 2068

Answers (2)

tanius
tanius

Reputation: 16759

You can also add the styling information into a <style> tag inside the HTML document. This works as of Qt 5.12, but seems to be undocumented behavior (at least style is not mentioned in the list of supported tags).

Your code would then be:

QString *html = new QString();
*html = "<html>"
        "  <head><style>table { border: 1px solid black; }</style></head>"
        "  <body>"
        "    <table border = 1>"
        "      <tr>" + name + "</tr>"
        "      <tr>" + surname + "</tr>"
        "      <tr>" + age + "</tr>"
        "    </table>"
        "  </body>"
        "</html>";
QTextDocument doc;
doc.setHtml(*html);

(Actually, I tested this only with the Qt QML Text element. But since it maps to QTextDocument internally, I'm pretty sure this also applies to QTextDocument itself. Apologies if not.)

Upvotes: 0

William Miller
William Miller

Reputation: 10320

The issue here is with the table property border (not to be confused with the CSS shorthand) must be set to a value greater than or equal to 1 otherwise no border will be displayed. Consider this code:

QString *html = new QString();
*html = "<table border = 1> <tr>" + name + "</tr>"
    "<tr>" + surname + "</tr>"
    "<tr>" + age + "</tr></table>";
QTextDocument doc;
doc.setDefaultStyleSheet("table { border: 1px solid black}");
doc.setHtml(*html);

Additionally, you mention in your answer that you have to add the style sheet after the setting the html, however the docs for QTextDocument seem to indicate otherwise:

The default style sheet is applied to all newly HTML formatted text that is inserted >into the document, for example using setHtml() or QTextCursor::insertHtml().

hence why setDefaultStylesheet() is before setHtml() in the above code.

Upvotes: 2

Related Questions