2
votes

I have a QPlainTextEdit widget that holds text that the user entered. The text might contain \n characters or it may all be on one very long line. My objective is to print this text on a printer (on paper) with word wrapping. The functions QPlainTextEdit::print() and QTextDocument::print() are not suitable to me because they both print the page number at the bottom of the page, which I don't want, and second, I can't seem to be able to control which pages to print (for example if the user only wants to print page #2 out of 5 pages) - the entire document is always printed.

Basically I am using a QPainter object to paint the text on the printer. The main difficulty I am facing is determining when to call QPrinter::newPage() function. How do you determine how much text will fit on a page? If the text is on one long line and the line is being word wrapped, how do you know when the first page is full and when to start a second page? I use the following code to draw:

painter.drawText(printer->pageRect(), Qt::TextWordWrap, ui->plainTextEdit->toPlainText());

painter is of type QPainter; printer is of type QPrinter; plainTextEdit is of type QPlainTextEdit.

1
you might need to you QFontMetrics to get size of text. - Kunal

1 Answers

0
votes

To get the vertical size of your text, call painter.boundingRect( painter.window(), myText ).height();. When that exceeds painter.window.height(), it's time to call newPage().

Now it's just a matter of building up your text word-by-word until the boundingRect height exceeds the page height. I'd suggest keeping a "safe" QString that you know will fit on a page and an "unsafe" QString that you just added the new word to. If the new word didn't exceed the height, then assign the safe string to the unsafe one. (Qt has some optimizations like shared copying to keep this from being too compute intensive).

To deal with individual words in a QString, you'll want to play with indexOf() or split() using their QRegExp variants so you can search for whitespace like spaces, tabs, newlines.

You'll have to account for a single "word" that itself won't fit on a page, and split it up mid-word. There may be other devils in the details but hopefully that gets you a good start.