Getting the bounding rect of a character in a QTextDocument
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:
And the code is:
Code:
void CQtTextLayout::GetXYWHOfLayoutIndex( int index, float *flX, float *flY, float *flW, float *flH )
{
if( m_pTextCursor )
{
m_pTextCursor->setPosition( index );
const QTextBlock textCursorBlock
= m_pTextCursor
->block
();
const QRectF blockBoundingRect
= m_pTextDocument
->documentLayout
()->blockBoundingRect
( textCursorBlock
);
const QTextLayout *textCursorBlockLayout
= textCursorBlock.
layout();
const int relativeCursorPositionInBlock = m_pTextCursor->position() - m_pTextCursor->block().position();
QTextLine textLine
= textCursorBlockLayout
->lineForTextPosition
( relativeCursorPositionInBlock
);
if ( textLine.isValid() ) {
int pos = m_pTextCursor->position() - m_pTextCursor->block().position();
*flY = textLine.lineNumber() * textLine.height() + blockBoundingRect.top();
*flX = textLine.cursorToX(pos) + rootFrameFormat.leftMargin() + rootFrameFormat.padding();
*flW = textLine.cursorToX(pos + 1) + rootFrameFormat.leftMargin() + rootFrameFormat.padding() - *flX;
*flH = textLine.height();
}
else
{
*flX = 0.0;
*flY = 0.0;
*flW = 0.0;
*flH = 0.0;
}
}
else
{
*flX = 0.0;
*flY = 0.0;
*flW = 0.0;
*flH = 0.0;
}
DebugLog( "GetXYWHOfLayoutIndex %.3f %.3f %.3f %.3f", *flX, *flY, *flW, *flH );
}