title: QTextDocument and selection painting
body: <p>I am painting a block of text on a widget with <code>QTextDocument::drawContents</code>. My current goal is to intercept mouse events and emulate text selection. It's pretty clear how to handle the mouse, but displaying the result puzzles me a lot.</p>
  <p>Just before we start: I can not use QLabel and let it handle selection on it's own (it has no idea how to draw unusual characters and messes up line height (<a href="https://git.macaw.me/blue/squawk/issues/59" rel="nofollow noreferrer">https://git.macaw.me/blue/squawk/issues/59</a>)), nor I can not use QTextBrowser there - it's just a message bubble, I'm not ready to sacrifice performance there.</p>
  <p>There is a very rich framework around QTextDocument, but I can not find any way to make it color the background of some fragment of text that I would consider selected. Found a way to make a frame around a text, found a way to draw under-over-lined text, but it looks like there is simply just no way this framework can draw a background behind text.</p>
  <p>I have tried doing this, to see if I can take selected fragment under some <code>QTextFrame</code> and set it's style:</p>
  <pre><code>QTextDocument* bodyRenderer = new QTextDocument();
  bodyRenderer-&gt;setHtml(&quot;some text&quot;);
  bodyRenderer-&gt;setTextWidth(50);
  painter-&gt;setBackgroundMode(Qt::BGMode::OpaqueMode); //this at least makes it color background under all text
  QTextFrameFormat format = bodyRenderer-&gt;rootFrame()-&gt;frameFormat();
  format.setBackground(option.palette.brush(QPalette::Active, QPalette::Highlight));
  bodyRenderer-&gt;rootFrame()-&gt;setFrameFormat(format);
  bodyRenderer-&gt;drawContents(painter);
  </code></pre>
  <p>Nothing of this works too:</p>
  <pre><code>QTextBlock b = bodyRenderer-&gt;begin();
  QTextBlockFormat format = b.blockFormat();
  format.setBackground(option.palette.brush(QPalette::Active, QPalette::Highlight));
  format.setProperty(QTextFormat::BackgroundBrush, option.palette.brush(QPalette::Active, QPalette::Highlight));
  QTextCursor cursor(bodyRenderer);
  cursor.setBlockFormat(format);
  b = bodyRenderer-&gt;begin();
  while (b.isValid() &gt; 0) {
      QTextLayout* lay = b.layout();
      QTextLayout::FormatRange range;
      range.format = b.charFormat();
      range.start = 0;
      range.length = 2;
      lay-&gt;draw(painter, option.rect.topLeft(), {range});
      b = b.next();
  }
  </code></pre>
  <p>Is there any way I can make this framework do a simple thing - draw a selection background behind some text? If not - is there a way I can unproject cursor position into coordinate translation, like can I do reverse operation from <code>QAbstractTextDocumentLayout::hitTest</code> just to understand where to draw that selection rectangle myself?</p>