CopperSpice API
1.9.2
|
There are a number of tasks which are often performed by developers when editing and processing text documents. These include the use of display widgets such as QTextBrowser and QTextEdit, creation of documents with QTextDocument, editing using a QTextCursor, and exporting the document structure. This document outlines some of the more common ways of using the rich text classes to perform these tasks, showing convenient patterns that can be reused in your own applications.
A text editor widget can be constructed and used to display HTML in the following way:
By default, the text editor contains a document with a root frame, inside which is an empty text block. This document can be obtained so that it can be modified directly by the application:
The text editor's cursor may also be used to edit a document:
Although a document can be edited using many cursors at once, a QTextEdit only displays a single cursor at a time. Therefore, if we want to update the editor to display a particular cursor or its selection, we need to set the editor's cursor after we have modified the document:
Text is selected by moving the cursor using operations that are similar to those performed by a user in a text editor. To select text between two points in the document, we need to position the cursor at the first point then move it using a special mode (QTextCursor::MoveMode) with a move operation (QTextCursor::MoveOperation). When we select the text, we leave the selection anchor at the old cursor position just as the user might do by holding down the Shift key when selecting text:
In the above code, a whole word is selected using this method. QTextCursor provides a number of common move operations for selecting individual characters, words, lines, and whole blocks.
QTextDocument provides a cursor-based interface for searching, making it easy to find and modify text in the style of a text editor. The following code finds all the instances of a particular word in a document, and changes the color of each:
The cursor does not have to be moved after each search and replace operation; it is always positioned at the end of the word that was just replaced.
QTextEdit is designed for the display of large rich text documents that are read on screen, rendering them in the same way as a web browser. As a result, it does not automatically break the contents of the document into page-sized pieces that are suitable for printing.
QTextDocument provides a print() function to allow documents to be printed using the QPrinter class. The following code shows how to prepare a document in a QTextEdit for printing with a QPrinter:
The document is obtained from the text editor, and a QPrinter is constructed then configured using a QPrintDialog. If the user accepts the printer's configuration then the document is formatted and printed using the print() function.