1

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
beep
  • 1,057
  • 2
  • 11
  • 23

2 Answers2

2

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.

William Miller
  • 9,839
  • 3
  • 25
  • 46
  • Thanks for the solution, it works now! However i am not able to do the same thing with `border-collapse`, but i think it's a problem with Qt(they probably haven't implemented it yet) – beep Nov 30 '18 at 19:46
  • 1
    I expect so, since that isn't listed in the [Supported HTML Subset](http://doc.qt.io/qt-5/richtext-html-subset.html) for `table`. I'm glad this answer helped - don't forget to accept it if it solved the problem – William Miller Nov 30 '18 at 19:54
0

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.)

tanius
  • 14,003
  • 3
  • 51
  • 63