![]() |
Home · Examples |
[Previous: The QTextCursor Interface][Rich Text Processing][Next: Advanced Rich Text Processing]
There are a number of tasks that are often performed by developers when editing and processing text documents using Qt. 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.
QTextEdit *editor = new QTextEdit(parent); editor->setHtml(aStringContainingHTMLtext); editor->show();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:
QTextDocument *document = editor->document();The text editor's cursor may also be used to edit a document:
QTextCursor cursor = editor->textCursor();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:
editor->setTextCursor(cursor);
cursor.movePosition(QTextCursor.MoveOperation.StartOfWord); cursor.movePosition(QTextCursor.MoveOperation.EndOfWord, QTextCursor.MoveMode.KeepAnchor);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.
QTextCursor newCursor = new QTextCursor(document); while (!newCursor.isNull() && !newCursor.atEnd()) { newCursor = document.find(searchString, newCursor); if (!newCursor.isNull()) { newCursor.movePosition(QTextCursor.MoveOperation.WordRight, QTextCursor.MoveMode.KeepAnchor); newCursor.mergeCharFormat(colorFormat); } }Note that 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.
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:
QTextDocument document = editor.document(); QPrinter printer = new QPrinter(); QPrintDialog dlg = new QPrintDialog(printer, this); if (dlg.exec() != QDialog.DialogCode.Accepted.value()) return; document.print(printer);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.
Copyright © 2008 Nokia | Trademarks | Qt Jambi 4.4.3_01 |