PDA

View Full Version : What's wrong with QTextLayout ?!



Cortex
19th December 2009, 13:50
Hi,
My QTextDocument is full of text.
However, when I run this code QTextLayout::lineCount() return always 0.


QTextBlock block = document->begin();
while(block.isValid())
{
QTextLayout *layout= block.layout();
int nbL=layout->lineCount();
qDebug( "count lines = %i", nbL );
}

Am I missing something?
What's wrong with it?

Plz help me guys, thanks.

wysota
19th December 2009, 15:53
What does block.text() return?

Cortex
19th December 2009, 16:46
block.text() does return the paragraph of each block.

wysota
19th December 2009, 18:43
Ok but I'm asking what it returns in your program :)

Cortex
19th December 2009, 22:15
Smart question !!
Well, hmm ok, am sorry I forgot the "block= block.next" :o , just in the thread ..

Here is a better exemple :


QTextDocument* document= new QTextDocument();
QTextCursor cursorTest(document);
cursorTest.movePosition(QTextCursor::Start);

cursorTest.insertText("Hello there");
cursorTest.insertBlock();
cursorTest.insertText("How are you?");
QTextBlock block = document->begin();
while(block.isValid())
{
QTextLayout *layout= block.layout();
qDebug()<<"Block content : "<<block.text() ;
qDebug()<<"Nb lines : "<<layout->lineCount();
block = block.next();
}

this code return :
>Block content : "Hello there"
>Nb lines : 0
>Block content : "How are you?"
>Nb lines : 0

is this normal?!

wysota
19th December 2009, 23:43
It can be normal. The docs say not all layouts support counting lines. And I don't see how could the document calculate the number of lines of the block if you didn't set the width of the document. Use QTextDocument::setTextWidth() and see if it changes anything.

Cortex
20th December 2009, 10:34
Unfortunately, setting the document text width didn't help.
However, I noticed in the QTextDocument doc a warning mentioned for some other functions (not the lineCount() ) :

Warning: This function only returns a valid value after the layout has been done.
So, I tried to call lineCount() after drawing the doc and it works.
This could explain the matter.

But am still in trouble:
Is there any way to "predict" the number of line of a block before being drawn?

wysota
20th December 2009, 10:58
If you don't know the width of text then no, because the layout is delayed for as long as possible. For simple layouts you may use QFontMetrics to guess the needed width of text. Alternatively you may try somehow forcing the layout to recalculate without drawing it on the screen (or whatever your destination paint device is).