2

I'm using a QPlainTextEdit control with word-wrapping active and I'm wondering how can I detect, in order to update a line counter, when a block of text gets wrapped (causing the number of lines to be incremented).

The underlying QTextDocument has a signal to detect when the block count changes, but not the corresponding one for line count changes.

Is it possible to detect word-wrapping and line count increase for a QTextDocument?

Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • check for the '\r\n' or the character count, usually each 80 characters is considered a line if i am not mistaken. – Hossein Sep 17 '14 at 17:57
  • 1
    @Hossein checking for end-of-line strings might get you a paragraph-count, but a line-count (in the context of a widget with word wrapping enabled) will depend on the width of the widget, and thus can vary even if the text string it is representing hasn't changed. – Jeremy Friesner Sep 17 '14 at 18:05
  • I've been thinking about detecting a block change and counting the characters (with respect to the control width) to see if the block fits into one line or in more than one, but that really feels heavy-weight. – Marco A. Sep 17 '14 at 18:44

2 Answers2

3

It's a little bit late but perhaps my answer can help somebody.
I had almost the same need in my company and I solved it like this:

// This example show how to get the visual number of lines
QPlainTextEdit *pte = new QPlainTextEdit();
pte->setAttribute(Qt::WA_DontShowOnScreen);
pte->show();
pte->setFixedWidth(50);
pte->setPlainText("Hello world!");
/* The next line return the number of necessary line
to display the text "Hello World!" with width of 50px */
int lineCount = pte->document()->documentLayout()->documentSize().height();

Best regards

thibsc
  • 3,747
  • 2
  • 18
  • 38
1

I solved by using QAbstractTextDocument's signal documentSizeChanged:

void QAbstractTextDocumentLayout::documentSizeChanged ( const QSizeF & newSize ) [signal]

This signal is emitted when the size of the document layout changes to newSize. Subclasses of QAbstractTextDocumentLayout should emit this signal when the document's entire layout size changes. This signal is useful for widgets that display text documents since it enables them to update their scroll bars correctly.

I know the size of my font and getting the precise size of the new underlying document allowed me to count the lines (wrapped or not) of my text document.

Marco A.
  • 43,032
  • 26
  • 132
  • 246