PDA

View Full Version : count line number in text



Alina
18th August 2006, 03:02
Hi all!
I got a server problem about counting the line number in a text.~~
a mouse click a text,the position of cursor follow clicking to change a new place.How do I kown where it is.....I mean the line number???????many thanks!!!!!!!:)

ball
18th August 2006, 03:16
Please read Qt4 documentation about the QTextCursor class.

jpn
18th August 2006, 08:29
As far as I know, there is no direct method to get the current line number. You might have to count it by yourself by iterating through the text blocks and comparing them to text cursors text block. Please someone correct me if I'm wrong! I hope I am, this isn't very convenient.. :)



int line = 0;
QTextBlock cursor = textCursor().block();
for (QTextBlock block = document()->begin(); block != document()->end(); block = block.next())
{
++line;
if (block == cursor)
break;
}
qDebug() << "line" << line;


This might become a little costly if it's calculated all the time when cursor moves...
It might be worth taking a quick look at this article:
Lazy updating for ascertaining block numbers in a document (http://qtnode.net/wiki/Lazy_updating_for_ascertaining_block_numbers_in_a_ document)