I am using QTextDocument for laying out some HTML text. This text gets rendered onto a QImage and its byte data is used to be displayed somewhere else.

Among other things I need to be able to get the x/y/w/h of a character in that QTextDocument. Based on some code here in the forum I am using the code below, but I am wondering whether there is an easier way to do that...

The class has two member variables:
Qt Code:
  1. QTextDocument *m_pTextDocument;
  2. QTextCursor *m_pTextCursor;
To copy to clipboard, switch view to plain text mode 

And the code is:
Qt Code:
  1. void CQtTextLayout::GetXYWHOfLayoutIndex( int index, float *flX, float *flY, float *flW, float *flH )
  2. {
  3. if( m_pTextCursor )
  4. {
  5. m_pTextCursor->setPosition( index );
  6.  
  7. const QTextBlock textCursorBlock = m_pTextCursor->block();
  8. const QRectF blockBoundingRect = m_pTextDocument->documentLayout()->blockBoundingRect( textCursorBlock );
  9. QTextFrameFormat rootFrameFormat = m_pTextDocument->rootFrame()->frameFormat();
  10.  
  11. const QTextLayout *textCursorBlockLayout = textCursorBlock.layout();
  12. const int relativeCursorPositionInBlock = m_pTextCursor->position() - m_pTextCursor->block().position();
  13. QTextLine textLine = textCursorBlockLayout->lineForTextPosition( relativeCursorPositionInBlock );
  14.  
  15. if ( textLine.isValid() ) {
  16. int pos = m_pTextCursor->position() - m_pTextCursor->block().position();
  17. *flY = textLine.lineNumber() * textLine.height() + blockBoundingRect.top();
  18. *flX = textLine.cursorToX(pos) + rootFrameFormat.leftMargin() + rootFrameFormat.padding();
  19. *flW = textLine.cursorToX(pos + 1) + rootFrameFormat.leftMargin() + rootFrameFormat.padding() - *flX;
  20. *flH = textLine.height();
  21. }
  22. else
  23. {
  24. *flX = 0.0;
  25. *flY = 0.0;
  26. *flW = 0.0;
  27. *flH = 0.0;
  28. }
  29. }
  30. else
  31. {
  32. *flX = 0.0;
  33. *flY = 0.0;
  34. *flW = 0.0;
  35. *flH = 0.0;
  36. }
  37. DebugLog( "GetXYWHOfLayoutIndex %.3f %.3f %.3f %.3f", *flX, *flY, *flW, *flH );
  38. }
To copy to clipboard, switch view to plain text mode