Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
richtext.qdoc
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*!
5 \group richtext-processing
6 \brief How to use Rich Text Processing APIs.
7 \title Rich Text Processing APIs
8*/
9
10/*!
11 \page richtext.html
12 \title Rich Text Processing
13 \brief Overview of Qt's rich text processing, editing, and display features.
14 \ingroup explanations-ui
15 \ingroup frameworks-technologies
16 \ingroup qt-basic-concepts
17
18 Qt provides a set of classes for creating, editing, and rendering
19 structured rich text documents. These classes center around QTextDocument,
20 which represents a rich text document with a well-defined internal
21 structure. Working directly with QTextDocument allows applications to
22 create, modify, and inspect rich text without relying on intermediate
23 markup formats.
24
25 You can access document information via two complementary interfaces:
26
27 \table
28 \header
29 \li Interface
30 \li Description
31 \row
32 \li Cursor-based interface (QTextCursor)
33 \li Supports editing operations that mimic user actions in a text
34 editor. Edits maintain the structural integrity of the underlying
35 document.
36 \row
37 \li Read-only hierarchical interface
38 \li Provides a high-level structural view of the document. It is
39 useful for tasks such as searching, inspection, and exporting
40 content.
41 \endtable
42
43 \section1 Rich Text Serialization
44
45 QTextDocument supports serialization to and from these markup formats:
46
47 \list
48 \li HTML: A defined subset of HTML is supported for loading and saving.
49 See \l {Supported HTML Subset}.
50 \li Markdown: QTextDocument can parse Markdown in both CommonMark and
51 GitHub dialects.
52 \endlist
53
54 \section1 Rich Text Topics
55
56 \list
57 \li \l{Rich Text Document Structure} describes the different elements
58 in a QTextDocument and how they are arranged in a document
59 structure.
60 \li \l{The QTextCursor Interface} explains how to edit rich text
61 documents using the cursor-based interface.
62 \li \l{Document Layouts} describes how to visually arrange document
63 contents.
64 \li \l{Common Rich Text Editing Tasks} describes frequently used
65 operations for reading and manipulating rich text such as selecting,
66 searching, and printing.
67 \li \l{Advanced Rich Text Processing} describes advanced rich text
68 editing tasks such as handling large files.
69 \li \l{Supported HTML Subset} lists the HTML tags supported by
70 QTextDocument.
71 \endlist
72
73 \section1 Rich Text Processing APIs
74
75 Qt provides an extensive collection of classes for parsing, rendering
76 manipulating and editing rich text.
77
78 \annotatedlist richtext-processing
79*/
80
81/*!
82 \page richtext-structure.html
83 \previouspage Rich Text Processing
84 \nextpage The QTextCursor Interface
85
86 \title Rich Text Document Structure
87
88 Text documents are represented by the QTextDocument class, which
89 contains information about the document's internal representation, its
90 structure, and keeps track of modifications to provide undo/redo
91 facilities.
92
93 The structured representation of a text document presents its contents as
94 a hierarchy of text blocks, frames, tables, and other objects. These provide
95 a logical structure to the document and describe how their contents will be
96 displayed. Generally, frames and tables are used to group other
97 structures while text blocks contain the actual textual information.
98
99 New elements are created and inserted into the document programmatically
100 \l{richtext-cursor.html}{with a QTextCursor} or by using an editor
101 widget, such as QTextEdit. Elements can be given a particular format when
102 they are created; otherwise they take the cursor's current format for the
103 element.
104
105 \table
106 \row
107 \li \inlineimage richtext-document.png
108 \li \b{Basic structure}
109
110 The "top level" of a document might be populated in the way shown.
111 Each document always contains a root frame, and this always contains
112 at least one text block.
113
114 For documents with some textual content, the root
115 frame usually contains a sequence of blocks and other elements.
116
117 Sequences of frames and tables are always separated by text blocks in a
118 document, even if the text blocks contain no information. This ensures that
119 new elements can always be inserted between existing structures.
120 \endtable
121
122 In this chapter, we look at each of the structural elements
123 used in a rich text document, outline their features and uses, and show
124 how to examine their contents. Document editing is described in
125 \l{richtext-cursor.html}{The QTextCursor Interface}.
126
127 \section1 Rich Text Documents
128
129 QTextDocument objects contain all the information required to construct
130 rich text documents.
131 Text documents can be accessed in two complementary ways: as a linear
132 buffer for editors to use, and as an object hierarchy that is useful to
133 layout engines.
134 In the hierarchical document model, objects generally correspond to
135 visual elements such as frames, tables, and lists. At a lower level,
136 these elements describe properties such as the text style and alignment.
137 The linear representation of the document is used for editing and
138 manipulation of the document's contents.
139
140 Although QTextEdit makes it easy to display and edit rich text, documents
141 can also be used independently of any editor widget, for example:
142
143 \snippet code/doc_src_richtext.cpp 0
144
145 Alternatively, they can be extracted from an existing editor:
146
147 \snippet code/doc_src_richtext.cpp 1
148
149 This flexibility enables applications to handle multiple rich text
150 documents without the overhead of multiple editor widgets, or requiring
151 documents to be stored in some intermediate format.
152
153 An empty document contains a root frame which itself contains a single
154 empty text block. Frames provide logical separation between parts of the document, but
155 also have properties that determine how they will appear when rendered.
156 A table is a specialized type of frame that consists of a number of
157 cells, arranged into rows and columns, each of which can contain
158 further structure and text. Tables provide management and layout
159 features that allow flexible configurations of cells to be created.
160
161 Text blocks contain text fragments, each of which specifies text and
162 character format information. Textual properties are defined both at
163 the character level and at the block level. At the character level,
164 properties such as font family, text color, and font weight can be
165 specified. The block level properties control the higher level
166 appearance and behavior of the text, such as the direction of text
167 flow, alignment, and background color.
168
169 The document structure is not manipulated directly. Editing is
170 performed through a cursor-based interface.
171 The \l{richtext-cursor.html}{text cursor interface}
172 automatically inserts new document elements into the root frame, and
173 ensures that it is padded with empty blocks where necessary.
174
175 We obtain the root frame in the following manner:
176
177 \snippet textdocument-frames/mainwindow.cpp rootframe
178
179 When navigating the document structure, it is useful to begin at the
180 root frame because it provides access to the entire document structure.
181
182
183 \section1 Document Elements
184
185 Rich text documents usually consist of common elements such as paragraphs,
186 frames, tables, and lists. These are represented in a QTextDocument
187 by the QTextBlock, QTextFrame, QTextTable, and QTextList classes.
188 Unlike the other elements in a document, images are represented by
189 specially formatted text fragments. This enables them to be placed
190 formatted inline with the surrounding text.
191
192 The basic structural building blocks in documents are QTextBlock and
193 QTextFrame. Blocks themselves contain fragments of rich text
194 (QTextFragment), but these do not directly influence the high level
195 structure of a document.
196
197 Elements which can group together other document elements are typically
198 subclasses of QTextObject, and fall into two categories: Elements that
199 group together text blocks are subclasses of QTextBlockGroup, and those
200 that group together frames and other elements are subclasses of QTextFrame.
201
202 \section2 Text Blocks
203
204 Text blocks are provided by the QTextBlock class.
205
206 Text blocks group together fragments of text with different character formats,
207 and are used to represent paragraphs in the document. Each block
208 typically contains a number of text fragments with different styles.
209 Fragments are created when text is inserted into the document, and more
210 of them are added when the document is edited. The document splits, merges,
211 and removes fragments to efficiently represent the different styles
212 of text in the block.
213
214 The fragments within a given block can be examined by using a
215 QTextBlock::iterator to traverse the block's internal structure:
216
217 \snippet textblock-fragments/xmlwriter.cpp 3
218 \snippet textblock-fragments/xmlwriter.cpp 5
219 \snippet textblock-fragments/xmlwriter.cpp 6
220
221 Blocks are also used to represent list items. As a result, blocks can
222 define their own character formats which contain information about
223 block-level decoration, such as the type of bullet points used for
224 list items. The formatting for the block itself is described by the
225 QTextBlockFormat class, and describes properties such as text alignment,
226 indentation, and background color.
227
228 Although a given document may contain complex structures, once we have a
229 reference to a valid block in the document, we can navigate between each
230 of the text blocks in the order in which they were written:
231
232 \snippet textblock-fragments/xmlwriter.cpp 0
233 \snippet textblock-fragments/xmlwriter.cpp 1
234 \snippet textblock-fragments/xmlwriter.cpp 2
235
236 This method is useful for when you want to extract just the rich text from a
237 document because it ignores frames, tables, and other types of structure.
238
239 QTextBlock provides comparison operators that make it easier to manipulate
240 blocks: \l{QTextBlock::operator==()}{operator==()} and
241 \l{QTextBlock::operator!=()}{operator!=()} are used to test whether two
242 blocks are the same, and \l{QTextBlock::operator<()}{operator<()} is used
243 to determine which one occurs first in a document.
244
245 \section2 Frames
246
247 Frames are provided by the QTextFrame class.
248
249 Text frames group together blocks of text and child frames, creating
250 document structures that are larger than paragraphs. The format of a frame
251 specifies how it is rendered and positioned on the page. Frames are
252 either inserted into the text flow, or they float on the left or right
253 hand side of the page.
254 Each document contains a root frame that contains all the other document
255 elements. As a result, all frames except the root frame have a parent
256 frame.
257
258 Since text blocks are used to separate other document elements, each
259 frame will always contain at least one text block, and zero or more
260 child frames. We can inspect the contents of a frame by using a
261 QTextFrame::iterator to traverse the frame's child elements:
262
263 \snippet textdocument-frames/mainwindow.cpp 4
264
265 Note that the iterator selects both frames and blocks, so it is necessary
266 to check which it is referring to. This allows us to navigate the document
267 structure on a frame-by-frame basis yet still access text blocks if
268 required. Both the QTextBlock::iterator and QTextFrame::iterator classes
269 can be used in complementary ways to extract the required structure from
270 a document.
271
272 \section2 Tables
273
274 Tables are provided by the QTextTable class.
275
276 Tables are collections of cells that are arranged in rows and columns.
277 Each table cell is a document element with its own character format, but it
278 can also contain other elements, such as frames and text blocks. Table cells
279 are automatically created when the table is constructed, or when extra rows
280 or columns are added. They can also be moved between tables.
281
282 QTextTable is a subclass of QTextFrame, so tables are treated like frames
283 in the document structure. For each frame that we encounter in the
284 document, we can test whether it represents a table, and deal with it in a
285 different way:
286
287 \snippet textdocument-tables/mainwindow.cpp 13
288
289 The cells within an existing table can be examined by iterating through
290 the rows and columns.
291
292 \snippet textdocument-tables/mainwindow.cpp 9
293 \snippet textdocument-tables/mainwindow.cpp 10
294 \snippet textdocument-tables/mainwindow.cpp 11
295 \snippet textdocument-tables/mainwindow.cpp 12
296
297
298 \section2 Lists
299
300 Lists are provided by the QTextList class.
301
302 Lists are sequences of text blocks that are formatted in the usual way, but
303 which also provide the standard list decorations such as bullet points and
304 enumerated items. Lists can be nested, and will be indented if the list's
305 format specifies a non-zero indentation.
306
307 We can refer to each list item by its index in the list:
308
309 \snippet textdocument-listitems/mainwindow.cpp 0
310 \snippet textdocument-listitems/mainwindow.cpp 1
311 \snippet textdocument-listitems/mainwindow.cpp 2
312
313 Since QTextList is a subclass of QTextBlockGroup, it does not group the
314 list items as child elements, but instead provides various functions for
315 managing them. This means that any text block we find when traversing a
316 document may actually be a list item. We can ensure that list items are
317 correctly identified by using the following code:
318
319 \snippet textdocument-listitems/mainwindow.cpp 3
320 \snippet textdocument-listitems/mainwindow.cpp 4
321 \snippet textdocument-listitems/mainwindow.cpp 5
322 \snippet textdocument-listitems/mainwindow.cpp 6
323 \snippet textdocument-listitems/mainwindow.cpp 7
324
325
326 \section2 Images
327
328 Images in QTextDocument are represented by text fragments that reference
329 external images via the resource mechanism. Images are created using the
330 cursor interface, and can be modified later by changing the character
331 format of the image's text fragment:
332
333 \snippet textdocument-imageformat/main.cpp 0
334 \snippet textdocument-imageformat/main.cpp 1
335 \snippet textdocument-imageformat/main.cpp 2
336
337 The fragment that represents the image can be found by iterating over
338 the fragments in the text block that contains the image.
339*/
340
341/*!
342 \page richtext-cursor.html
343 \previouspage Rich Text Document Structure
344 \nextpage Document Layouts
345
346 \title The QTextCursor Interface
347
348 Documents can be edited via the interface provided by the QTextCursor
349 class; cursors are either created using a constructor or obtained from
350 an editor widget. The cursor is used to perform editing operations that
351 correspond exactly to those the user is able to make themselves in an
352 editor. As a result, information about the document structure is also
353 available through the cursor, and this allows the structure to be
354 modified. The use of a cursor-oriented interface for editing makes the
355 process of writing a custom editor simpler for developers, since the
356 editing operations can be easily visualized.
357
358 The QTextCursor class also maintains information about any text it
359 has selected in the document, again following a model that is
360 conceptually similar to the actions made by the user to select text
361 in an editor.
362
363 Rich text documents can have multiple cursors
364 associated with them, and each of these contains information about their
365 position in the document and any selections that they may hold. This
366 cursor-based paradigm makes common operations, such as cutting and pasting
367 text, simple to implement programmatically, yet it also allows more complex
368 editing operations to be performed on the document.
369
370 This chapter describes most of the common editing operations that you
371 will need to perform using a cursor, from basic insertion of text and
372 document elements to more complex manipulation of document structures.
373
374 \section1 Cursor-Based Editing
375
376 At the simplest level, text documents are made up of a string of characters,
377 marked up in some way to represent the block structure of the text within the
378 document. QTextCursor provides a cursor-based interface that allows the
379 contents of a QTextDocument to be manipulated at the character level. Since
380 the elements (blocks, frames, tables, etc.) are also encoded in the character
381 stream, the document structure can itself be changed by the cursor.
382
383 The cursor keeps track of its location within its parent document, and can
384 report information about the surrounding structure, such as the enclosing
385 text block, frame, table, or list. The formats of the enclosing structures
386 can also be directly obtained through the cursor.
387
388 \section2 Using a Cursor
389
390 The main use of a cursor is to insert or modify text within a block.
391 We can use a text editor's cursor to do this:
392
393 \snippet textblock-formats/main.cpp 0
394
395 Alternatively, we can obtain a cursor directly from a document:
396
397 \snippet textdocument-images/main.cpp 0
398
399 The cursor is positioned at the start of the document so that we can write
400 into the first (empty) block in the document.
401
402 \section2 Grouping Cursor Operations
403
404 A series of editing operations can be packaged together so that they can
405 be replayed, or undone together in a single action. This is achieved by
406 using the \c beginEditBlock() and \c endEditBlock() functions in the
407 following way, as in the following example where we select the word that
408 contains the cursor:
409
410 \snippet textdocument-selections/mainwindow.cpp 0
411
412 If editing operations are not grouped, the document automatically records
413 the individual operations so that they can be undone later. Grouping
414 operations into larger packages can make editing more efficient both for
415 the user and for the application, but care has to be taken not to group too
416 many operations together as the user may want find-grained control over the
417 undo process.
418
419 \section2 Multiple Cursors
420
421 Multiple cursors can be used to simultaneously edit the same document,
422 although only one will be visible to the user in a QTextEdit widget.
423 The QTextDocument ensures that each cursor writes text correctly and
424 does not interfere with any of the others.
425
426 \omit
427 \snippet textdocument-cursors/main.cpp 0
428 \snippet textdocument-cursors/main.cpp 1
429 \endomit
430
431 \section1 Inserting Document Elements
432
433 QTextCursor provides several functions that can be used to change the
434 structure of a rich text document. Generally, these functions allow
435 document elements to be created with relevant formatting information,
436 and they are inserted into the document at the cursor's position.
437
438 The first group of functions insert block-level elements, and update the
439 cursor position, but they do not return the element that was inserted:
440
441 \list
442 \li \l{QTextCursor::insertBlock()}{insertBlock()} inserts a new text block
443 (paragraph) into a document at the cursor's position, and moves the
444 cursor to the start of the new block.
445 \li \l{QTextCursor::insertFragment()}{insertFragment()} inserts an existing
446 text fragment into a document at the cursor's position.
447 \li \l{QTextCursor::insertImage()}{insertImage()} inserts an image into a
448 document at the cursor's position.
449 \li \l{QTextCursor::insertText()}{insertText()} inserts text into the
450 document at the cursor's position.
451 \endlist
452
453 You can examine the contents of the element that was inserted through the
454 cursor interface.
455
456 The second group of functions insert elements that provide structure to
457 the document, and return the structure that was inserted:
458
459 \list
460 \li \l{QTextCursor::insertFrame()}{insertFrame()} inserts a frame into the
461 document \e after the cursor's current block, and moves the cursor to
462 the start of the empty block in the new frame.
463 \li \l{QTextCursor::insertList()}{insertList()} inserts a list into the
464 document at the cursor's position, and moves the cursor to the start
465 of the first item in the list.
466 \li \l{QTextCursor::insertTable()}{insertTable()} inserts a table into
467 the document \e after the cursor's current block, and moves the cursor
468 to the start of the block following the table.
469 \endlist
470
471 These elements either contain or group together other elements in the
472 document.
473
474 \section2 Text and Text Fragments
475
476 Text can be inserted into the current block in the current character
477 format, or in a custom format that is specified with the text:
478
479 \snippet textdocument-charformats/main.cpp 0
480
481 Once the character format has been used with a cursor, that format becomes
482 the default format for any text inserted with that cursor until another
483 character format is specified.
484
485 If a cursor is used to insert text without specifying a character format,
486 the text will be given the character format used at that position in the
487 document.
488
489 \section2 Blocks
490
491 Text blocks are inserted into the document with the
492 \l{QTextCursor::insertBlock()}{insertBlock()} function.
493
494 \snippet textblock-formats/main.cpp 1
495
496 The cursor is positioned at the start of the new block.
497
498 \section2 Frames
499
500 Frames are inserted into a document using the cursor, and will be placed
501 within the cursor's current frame \e after the current block.
502 The following code shows how a frame can be inserted between two text
503 blocks in a document's root frame. We begin by finding the cursor's
504 current frame:
505
506 \snippet textdocument-frames/mainwindow.cpp 0
507
508 We insert some text in this frame then set up a frame format for the
509 child frame:
510
511 \snippet textdocument-frames/mainwindow.cpp 1
512
513 The frame format will give the frame an external margin of 32 pixels,
514 internal padding of 8 pixels, and a border that is 4 pixels wide.
515 See the QTextFrameFormat documentation for more information about
516 frame formats.
517
518 The frame is inserted into the document after the preceding text:
519
520 \snippet textdocument-frames/mainwindow.cpp 2
521
522 We add some text to the document immediately after we insert the frame.
523 Since the text cursor is positioned \e{inside the frame} when it is inserted
524 into the document, this text will also be inserted inside the frame.
525
526 Finally, we position the cursor outside the frame by taking the last
527 available cursor position inside the frame we recorded earlier:
528
529 \snippet textdocument-frames/mainwindow.cpp 3
530
531 The text that we add last is inserted after the child frame in the
532 document. Since each frame is padded with text blocks, this ensures that
533 more elements can always be inserted with a cursor.
534
535 \section2 Tables
536
537 Tables are inserted into the document using the cursor, and will be
538 placed within the cursor's current frame \e after the current block:
539
540 \snippet textdocument-tables/mainwindow.cpp 0
541 \snippet textdocument-tables/mainwindow.cpp 3
542
543 Tables can be created with a specific format that defines the overall
544 properties of the table, such as its alignment, background color, and
545 the cell spacing used. It can also determine the constraints on each
546 column, allowing each of them to have a fixed width, or resize according
547 to the available space.
548
549 \snippet textdocument-tables/mainwindow.cpp 2
550
551 The columns in the table created above will each take up a certain
552 percentage of the available width. Note that the table format is
553 optional; if you insert a table without a format, some sensible
554 default values will be used for the table's properties.
555
556 Since cells can contain other document elements, they too can be
557 formatted and styled as necessary.
558
559 Text can be added to the table by navigating to each cell with the cursor
560 and inserting text.
561
562 \snippet textdocument-tables/mainwindow.cpp 4
563
564 We can create a simple timetable by following this approach:
565
566 \snippet textdocument-tables/mainwindow.cpp 5
567 \snippet textdocument-tables/mainwindow.cpp 6
568 \snippet textdocument-tables/mainwindow.cpp 7
569 \snippet textdocument-tables/mainwindow.cpp 8
570
571 \section2 Lists
572
573 Lists of block elements can be automatically created and inserted into the
574 document at the current cursor position. Each list that is created in this
575 way requires a list format to be specified:
576
577 \snippet textdocument-lists/mainwindow.cpp 0
578
579 The above code first checks whether the cursor is within an existing list
580 and, if so, gives the list format for the new list a suitable level of
581 indentation. This allows nested lists to be created with increasing
582 levels of indentation. A more sophisticated implementation would also use
583 different kinds of symbol for the bullet points in each level of the list.
584
585 \section2 Images
586
587 Inline images are added to documents through the cursor in the usual manner.
588 Unlike many other elements, all of the image properties are specified by the
589 image's format. This means that a QTextImageFormat object has to be
590 created before an image can be inserted:
591
592 \snippet textdocument-images/main.cpp 1
593
594 The image name refers to an entry in the application's resource file.
595 The method used to derive this name is described in
596 \l{resources.html}{The Qt Resource System}.
597
598 \section1 Examples
599
600 Rich text is stored in text documents that can either be created by
601 importing HTML from an external source, or generated using a QTextCursor.
602
603 \section2 Manipulating Rich Text
604
605 The easiest way to use a rich text document is through
606 the QTextEdit class, providing an editable view onto a document. The code
607 below imports HTML into a document, and displays the document using a
608 text edit widget.
609
610 \snippet scribe-overview/main.cpp 1
611
612 You can retrieve the document from the text edit using the
613 document() function. The document can then be edited programmatically
614 using the QTextCursor class. This class is modeled after a screen
615 cursor, and editing operations follow the same semantics. The following
616 code changes the first line of the document to a bold font, leaving all
617 other font properties untouched. The editor will be automatically
618 updated to reflect the changes made to the underlying document data.
619
620 \snippet scribe-overview/main.cpp 0
621
622 Note that the cursor was moved from the start of the first line to the
623 end, but that it retained an anchor at the start of the line. This
624 demonstrates the cursor-based selection facilities of the
625 QTextCursor class.
626
627 \section2 Generating a Calendar
628
629 Rich text can be generated very quickly using the cursor-based
630 approach. The following example shows a simple calendar in a
631 QTextEdit widget with bold headers for the days of the week:
632
633 \snippet textdocument-blocks/mainwindow.cpp 0
634 \codeline
635 \snippet textdocument-blocks/mainwindow.cpp 1
636 \snippet textdocument-blocks/mainwindow.cpp 2
637 \snippet textdocument-blocks/mainwindow.cpp 3
638
639 The above example demonstrates how simple it is to quickly generate new
640 rich text documents using a minimum amount of code. Although we have
641 generated a crude fixed-pitch calendar to avoid quoting too much code,
642 Scribe provides much more sophisticated layout and formatting features.
643*/
644
645/*!
646 \page richtext-layouts.html
647 \previouspage The QTextCursor Interface
648 \nextpage Common Rich Text Editing Tasks
649
650 \title Document Layouts
651
652 The layout of a document is only relevant when it is to be displayed on
653 a device, or when some information is requested that requires a visual
654 representation of the document. Until this occurs, the document does
655 not need to be formatted and prepared for a device.
656
657 \section1 Overview
658
659 Each document's layout is managed by a subclass of the
660 QAbstractTextDocumentLayout class. This class provides a common
661 interface for layout and rendering engines. The default rendering
662 behavior is currently implemented in a private class. This approach
663 makes it possible to create custom layouts, and provides the
664 mechanism used when preparing pages for printing or exporting to
665 Portable Document Format (PDF) files.
666
667 \section1 Example - Shaped Text Layout
668
669 Sometimes it is important to be able to format plain text within an
670 irregularly-shaped region, perhaps when rendering a custom widget, for
671 example. Scribe provides generic features, such as those provided by
672 the QTextLayout class, to help developers perform word-wrapping and
673 layout tasks without the need to create a document first.
674
675 \image plaintext-layout.webp {Screenshot of a text that flows around a
676 circle.}
677
678 Formatting and drawing a paragraph of plain text is straightforward.
679 The example below will lay out a paragraph of text, using a single
680 font, around the right hand edge of a circle.
681
682 \snippet plaintextlayout/window.cpp 0
683
684 We create a text layout, specifying the text string we want to display
685 and the font to use. We ensure that the text we supplied is formatted
686 correctly by obtaining text lines from the text format, and wrapping
687 the remaining text using the available space. The lines are positioned
688 as we move down the page.
689
690 The formatted text can be drawn onto a paint device; in the above code,
691 the text is drawn directly onto a widget.
692 */
693
694 /*!
695 \page richtext-common-tasks.html
696 \previouspage Document Layouts
697 \nextpage Advanced Rich Text Processing
698
699 \title Common Rich Text Editing Tasks
700
701 There are a number of tasks that are often performed by developers
702 when editing and processing text documents using Qt. These include the use
703 of display widgets such as QTextBrowser and QTextEdit, creation of
704 documents with QTextDocument, editing using a QTextCursor, and
705 exporting the document structure.
706 This document outlines some of the more common ways of using the rich
707 text classes to perform these tasks, showing convenient patterns that can
708 be reused in your own applications.
709
710 \section1 Using QTextEdit
711
712 A text editor widget can be constructed and used to display HTML in the
713 following way:
714
715 \snippet code/doc_src_richtext.cpp 2
716
717 By default, the text editor contains a document with a root frame, inside
718 which is an empty text block. This document can be obtained so that it can
719 be modified directly by the application:
720
721 \snippet code/doc_src_richtext.cpp 3
722
723 The text editor's cursor may also be used to edit a document:
724
725 \snippet code/doc_src_richtext.cpp 4
726
727 Although a document can be edited using many cursors at once, a QTextEdit
728 only displays a single cursor at a time. Therefore, if we want to update the
729 editor to display a particular cursor or its selection, we need to set the
730 editor's cursor after we have modified the document:
731
732 \snippet code/doc_src_richtext.cpp 5
733
734 \section1 Selecting Text
735
736 Text is selected by moving the cursor using operations that are similar to
737 those performed by a user in a text editor. To select text between two
738 points in the document, we need to position the cursor at the first point
739 then move it using a special mode (\l{QTextCursor::MoveMode}) with a
740 move operation (\l{QTextCursor::MoveOperation}).
741 When we select the text, we leave the selection anchor at the old cursor
742 position just as the user might do by holding down the Shift key when
743 selecting text:
744
745 \snippet textdocument-selections/mainwindow.cpp 1
746
747 In the above code, a whole word is selected using this method. QTextCursor
748 provides a number of common move operations for selecting individual
749 characters, words, lines, and whole blocks.
750
751 \section1 Finding Text
752
753 QTextDocument provides a cursor-based interface for searching, making
754 it easy to find and modify text in the style of a text editor. The following
755 code finds all the instances of a particular word in a document, and changes
756 the color of each:
757
758 \snippet textdocument-find/main.cpp 0
759 \snippet textdocument-find/main.cpp 1
760
761 Note that the cursor does not have to be moved after each search and replace
762 operation; it is always positioned at the end of the word that was just
763 replaced.
764
765 \section1 Printing Documents
766
767 QTextEdit is designed for the display of large rich text documents that are
768 read on screen, rendering them in the same way as a web browser. As a result,
769 it does not automatically break the contents of the document into page-sized
770 pieces that are suitable for printing.
771
772 QTextDocument provides a \l{QTextDocument::print()}{print()} function to
773 allow documents to be printed using the QPrinter class. The following code
774 shows how to prepare a document in a QTextEdit for printing with a QPrinter:
775
776 \snippet textdocument-printing/mainwindow.cpp 0
777
778 The document is obtained from the text editor, and a QPrinter is constructed
779 then configured using a QPrintDialog. If the user accepts the printer's
780 configuration then the document is formatted and printed using the
781 \l{QTextDocument::print()}{print()} function.
782*/
783
784/*!
785 \page richtext-advanced-processing.html
786 \previouspage Common Rich Text Editing Tasks
787 \nextpage Supported HTML Subset
788
789 \title Advanced Rich Text Processing
790
791 \section1 Handling Large Files
792
793 Qt does not limit the size of files that are used for text
794 processing. In most cases, this will not present a problem. For
795 especially large files, however, you might experience that your
796 application will become unresponsive or that you will run out of
797 memory. The size of the files you can load depends on your
798 hardware and on Qt's and your own application's implementation.
799
800 If you are faced with this problem, we recommend that you address the
801 following issues:
802
803 \list
804 \li You should consider breaking up large paragraphs into smaller
805 ones as Qt handles small paragraphs better. You could also
806 insert line breaks at regular intervals, which will look the
807 same as one large paragraph in a QTextEdit.
808 \li You can reduce the amount of blocks in a QTextDocument with
809 \l{QTextDocument::}{maximumBlockCount()}. The document is only
810 as large as the number of blocks as far as QTextEdit is concerned.
811 \li When adding text to a text edit, it is an advantage to add it
812 in an edit block (see example below). The result is that the
813 text edit does not need to build the entire document structure at once.
814 \endlist
815
816 We give an example of the latter technique from the list. We assume that
817 the text edit is visible.
818
819 \snippet code/doc_src_richtext.cpp 6
820
821 \omit
822 Ideas for other sections:
823
824 * Hiding QTextBlock elements.
825 * Changing the word wrapping mode in QTextEdit. Custom word wrapping?
826 \endomit
827*/
828
829/*!
830 \page richtext-html-subset.html
831 \title Supported HTML Subset
832 \brief Describes the support for HTML markup in text widgets.
833
834 \previouspage Common Rich Text Editing Tasks
835
836 Qt's text widgets are able to display rich text, specified using a subset of \l {http://www.w3.org/TR/html401/}{HTML 4}
837 markup. Widgets that use QTextDocument, such as QLabel and QTextEdit, are able to display
838 rich text specified in this way.
839
840 \section1 Using HTML Markup in Text Widgets
841
842 Widgets automatically detect HTML markup and display rich text accordingly. For example,
843 setting a label's \l{QLabel::}{text} property with the string \c{"<b>Hello</b> <i>Qt!</i>"}
844 will result in the label displaying text like this: \b{Hello} \e{Qt!}
845
846 When HTML markup is used for text, Qt follows the rules defined by the \l{http://www.w3.org/TR/html401/}{HTML 4}
847 specification. This includes default properties for text layout, such as the
848 direction of the text flow (left-to-right) which can be changed by applying the
849 \l{#Block Attributes}{\c dir} attribute to blocks of text.
850
851 \section1 Supported Tags
852
853 The following table lists the HTML tags supported by Qt's
854 \l{Rich Text Processing}{rich text} engine.
855
856 \note The functionality implemented for tags listed below is a subset of
857 the full HTML 4 specification. Not all attributes are supported,
858 see comments for each tag.
859
860 \table 70%
861 \header \li Tag
862 \li Description
863 \li Comment
864 \row \li \c a
865 \li Anchor or link
866 \li Supports the \c href and \c name attributes.
867 \row \li \c address
868 \li Address
869 \li
870 \row \li \c b
871 \li Bold
872 \li
873 \row \li \c big
874 \li Larger font
875 \li
876 \row \li \c blockquote
877 \li Indented paragraph
878 \li
879 \row \li \c body
880 \li Document body
881 \li Supports the \c bgcolor attribute, which
882 can be a Qt \l{QColor::fromString()}{color name}
883 or a \c #RRGGBB color specification.
884 \row \li \c br
885 \li Line break
886 \li
887 \row \li \c center
888 \li Centered paragraph
889 \li
890 \row \li \c cite
891 \li Inline citation
892 \li Same as \c i.
893 \row \li \c code
894 \li Code
895 \li Same as \c tt.
896 \row \li \c dd
897 \li Definition data
898 \li
899 \row \li \c del
900 \li Deleted
901 \li Same as \c s. Since Qt 6.11
902 \row \li \c dfn
903 \li Definition
904 \li Same as \c i.
905 \row \li \c div
906 \li Document division
907 \li Supports the standard \l{block attributes}.
908 \row \li \c dl
909 \li Definition list
910 \li Supports the standard \l{block attributes}.
911 \row \li \c dt
912 \li Definition term
913 \li Supports the standard \l{block attributes}.
914 \row \li \c em
915 \li Emphasized
916 \li Same as \c i.
917 \row \li \c font
918 \li Font size, family, and/or color
919 \li Supports the following attributes:
920 \c size, \c face, and \c color (Qt
921 \l{QColor::fromString()}{color names} or
922 \c #RRGGBB).
923 \row \li \c h1
924 \li Level 1 heading
925 \li Supports the standard \l{block attributes}.
926 \row \li \c h2
927 \li Level 2 heading
928 \li Supports the standard \l{block attributes}.
929 \row \li \c h3
930 \li Level 3 heading
931 \li Supports the standard \l{block attributes}.
932 \row \li \c h4
933 \li Level 4 heading
934 \li Supports the standard \l{block attributes}.
935 \row \li \c h5
936 \li Level 5 heading
937 \li Supports the standard \l{block attributes}.
938 \row \li \c h6
939 \li Level 6 heading
940 \li Supports the standard \l{block attributes}.
941 \row \li \c head
942 \li Document header
943 \li
944 \row \li \c hr
945 \li Horizontal line
946 \li Supports the \c width attribute, which can
947 be specified as an absolute or relative (\c %) value.
948 \row \li \c html
949 \li HTML document
950 \li
951 \row \li \c i
952 \li Italic
953 \li
954 \row \li \c img
955 \li Image
956 \li Supports the \c src, \c source
957 (for Qt 3 compatibility), \c width, and \c height
958 attributes.
959 \row \li \c kbd
960 \li User-entered text
961 \li
962 \row \li \c meta
963 \li Meta-information
964 \li If a text encoding is specified using the \c{meta}
965 tag, it is picked up by Qt::codecForHtml(). Likewise,
966 if an encoding is specified to QTextDocument::toHtml(),
967 the encoding is stored using a \c meta tag, for
968 example:
969 \c {<meta http-equiv="Content-Type" content="text/html; charset=EUC-JP" />}
970 \row \li \c li
971 \li List item
972 \li
973 \row \li \c nobr
974 \li Non-breakable text
975 \li
976 \row \li \c ol
977 \li Ordered list
978 \li Supports the standard \l{list attributes}.
979 \row \li \c p
980 \li Paragraph
981 \li Left-aligned by default. Supports the standard
982 \l{block attributes}.
983 \row \li \c pre
984 \li Preformated text
985 \li
986 \row \li \c qt
987 \li Qt rich-text document
988 \li Synonym for \c html. Provided for compatibility with
989 earlier versions of Qt.
990 \row \li \c s
991 \li Strikethrough
992 \li
993 \row \li \c samp
994 \li Sample code
995 \li Same as \c tt.
996 \row \li \c small
997 \li Small font
998 \li
999 \row \li \c span
1000 \li Grouped elements
1001 \li
1002 \row \li \c strong
1003 \li Strong
1004 \li Same as \c b.
1005 \row \li \c sub
1006 \li Subscript
1007 \li
1008 \row \li \c sup
1009 \li Superscript
1010 \li
1011 \row \li \c table
1012 \li Table
1013 \li Supports the following attributes: \c border,
1014 \c bgcolor (Qt \l{QColor::fromString()}{color names}
1015 or \c #RRGGBB), \c cellspacing, \c cellpadding,
1016 \c width (absolute or relative), and \c height.
1017 \row \li \c tbody
1018 \li Table body
1019 \li Does nothing.
1020 \row \li \c td
1021 \li Table data cell
1022 \li Supports the standard \l{table cell attributes}.
1023 \row \li \c tfoot
1024 \li Table footer
1025 \li Does nothing.
1026 \row \li \c th
1027 \li Table header cell
1028 \li Supports the standard \l{table cell attributes}.
1029 \row \li \c thead
1030 \li Table header
1031 \li If the \c thead tag is specified, it is used when printing tables
1032 that span multiple pages.
1033 \row \li \c title
1034 \li Document title
1035 \li The value specified using the \c
1036 title tag is available through
1037 QTextDocument::metaInformation().
1038 \row \li \c tr
1039 \li Table row
1040 \li Supports the \c bgcolor attribute, which
1041 can be a Qt \l{QColor::fromString()}{color name}
1042 or a \c #RRGGBB color specification.
1043 \row \li \c tt
1044 \li Typewrite font
1045 \li
1046 \row \li \c u
1047 \li Underlined
1048 \li
1049 \row \li \c ul
1050 \li Unordered list
1051 \li Supports the standard \l{list attributes}.
1052 \row \li \c var
1053 \li Variable
1054 \li Same as \c i.
1055 \endtable
1056
1057 \section1 Block Attributes
1058
1059 The following attributes are supported by the \c div, \c dl, \c
1060 dt, \c h1, \c h2, \c h3, \c h4, \c h5, \c h6, \c p tags:
1061
1062 \list
1063 \li \c align (\c left, \c right, \c center, \c justify)
1064 \li \c dir (\c ltr, \c rtl)
1065 \endlist
1066
1067 \section1 List Attributes
1068
1069 The following attribute is supported by the \c ol and \c ul tags:
1070
1071 \list
1072 \li \c type (\c 1, \c a, \c A, \c square, \c disc, \c circle)
1073 \endlist
1074
1075 Additionally, the following attribute is supported by the \c ol tag:
1076
1077 \list
1078 \li \c start
1079 \endlist
1080
1081 \section1 Table Cell Attributes
1082
1083 The following attributes are supported by the \c td and \c th
1084 tags:
1085
1086 \list
1087 \li \c width (absolute, relative, or no-value)
1088 \li \c bgcolor (Qt \l{QColor::fromString()}{color names} or \c #RRGGBB)
1089 \li \c colspan
1090 \li \c rowspan
1091 \li \c align (\c left, \c right, \c center, \c justify)
1092 \li \c valign (\c top, \c middle, \c bottom)
1093 \endlist
1094
1095 \section1 CSS Properties
1096 The following table lists the CSS properties supported by Qt's
1097 \l{Rich Text Processing}{rich text} engine:
1098
1099 \table
1100 \header \li Property
1101 \li Values
1102 \li Description
1103 \row
1104 \li \c background-color
1105 \li <color>
1106 \li Background color for elements
1107 \row
1108 \li \c background-image
1109 \li <uri>
1110 \li Background image for elements
1111 \row \li \c color
1112 \li <color>
1113 \li Text foreground color
1114 \row \li \c font-family
1115 \li <family name>
1116 \li Font family name
1117 \row \li \c font-size
1118 \li [ small | medium | large | x-large | xx-large ] | <size>pt | <size>px
1119 \li Font size relative to the document font, or specified in points or pixels
1120 \row \li \c font-style
1121 \li [ normal | italic | oblique ]
1122 \li
1123 \row \li \c font-weight
1124 \li [ normal | bold | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 ]
1125 \li Specifies the font weight used for text, where \c normal and \c bold
1126 are mapped to the corresponding QFont weights. Numeric values are
1127 8 times the equivalent QFont weight values.
1128 \row \li \c text-decoration
1129 \li none | [ underline || overline || line-through ]
1130 \li Additional text effects
1131 \row \li \c font
1132 \li [ [ <'font-style'> || <'font-weight'> ]? <'font-size'> <'font-family'> ]
1133 \li Font shorthand property
1134 \row \li \c text-indent
1135 \li <length>px
1136 \li First line text indentation in pixels
1137 \row \li \c white-space
1138 \li normal | pre | nowrap | pre-wrap
1139 \li Declares how whitespace in HTML is handled.
1140 \row \li \c margin-top
1141 \li <length>px
1142 \li Top paragraph margin in pixels
1143 \row \li \c margin-bottom
1144 \li <length>px
1145 \li Bottom paragraph margin in pixels
1146 \row \li \c margin-left
1147 \li <length>px
1148 \li Left paragraph margin in pixels
1149 \row \li \c margin-right
1150 \li <length>px
1151 \li Right paragraph margin in pixels
1152 \row \li \c padding-top
1153 \li <length>px
1154 \li Top table cell padding in pixels
1155 \row \li \c padding-bottom
1156 \li <length>px
1157 \li Bottom table cell padding in pixels
1158 \row \li \c padding-left
1159 \li <length>px
1160 \li Left table cell padding in pixels
1161 \row \li \c padding-right
1162 \li <length>px
1163 \li Right table cell padding in pixels
1164 \row \li \c padding
1165 \li <length>px
1166 \li Shorthand for setting all the padding properties at once.
1167 \row \li \c vertical-align
1168 \li baseline | sub | super | middle | top | bottom
1169 \li Vertical text alignment. For vertical alignment in text table cells only middle, top, and bottom apply.
1170 \row \li \c border-collapse
1171 \li collapse | separate
1172 \li Border Collapse mode for text tables. If set to collapse, cell-spacing will not be applied.
1173 \row \li \c border-color
1174 \li <color>
1175 \li Border color for text tables and table cells.
1176 \row \li \c border-top-color
1177 \li <color>
1178 \li Top border color for table cells.
1179 \row \li \c border-bottom-color
1180 \li <color>
1181 \li Bottom border color for table cells.
1182 \row \li \c border-left-color
1183 \li <color>
1184 \li Left border color for table cells.
1185 \row \li \c border-right-color
1186 \li <color>
1187 \li Right border color for table cells.
1188 \row \li \c border-style
1189 \li none | dotted | dashed | dot-dash | dot-dot-dash | solid | double | groove | ridge | inset | outset
1190 \li Border style for text tables and table cells.
1191 \row \li \c border-top-style
1192 \li <border-style>
1193 \li Top border style for table cells.
1194 \row \li \c border-bottom-style
1195 \li <border-style>
1196 \li Bottom border style for table cells.
1197 \row \li \c border-left-style
1198 \li <border-style>
1199 \li Left border style for table cells.
1200 \row \li \c border-right-style
1201 \li <border-style>
1202 \li Right border style for table cells.
1203 \row \li \c border-width
1204 \li <width>px
1205 \li Width of table or cell border
1206 \row \li \c border-top-width
1207 \li <length>px
1208 \li Top border width for table cells.
1209 \row \li \c border-bottom-width
1210 \li <length>px
1211 \li Bottom border width for table cells.
1212 \row \li \c border-left-width
1213 \li <length>px
1214 \li Left border width for table cells.
1215 \row \li \c border-right-width
1216 \li <length>px
1217 \li Right border width for table cells.
1218 \row \li \c border-top
1219 \li <width>px <border-style> <border-color>
1220 \li Shorthand for setting top border width, style and color
1221 \row \li \c border-bottom
1222 \li <width>px <border-style> <border-color>
1223 \li Shorthand for setting bottom border width, style and color
1224 \row \li \c border-left
1225 \li <width>px <border-style> <border-color>
1226 \li Shorthand for setting left border width, style and color
1227 \row \li \c border-right
1228 \li <width>px <border-style> <border-color>
1229 \li Shorthand for setting right border width, style and color
1230 \row \li \c border-top
1231 \li <width>px <border-style> <border-color>
1232 \li Shorthand for setting top border width, style and color
1233 \row \li \c border-bottom
1234 \li <width>px <border-style> <border-color>
1235 \li Shorthand for setting bottom border width, style and color
1236 \row \li \c border
1237 \li <width>px <border-style> <border-color>
1238 \li Shorthand for setting all four border's width, style and color
1239 \row \li \c background
1240 \li [ <'background-color'> || <'background-image'> ]
1241 \li Background shorthand property
1242 \row \li \c page-break-before
1243 \li [ auto | always ]
1244 \li Make it possible to enforce a page break before the paragraph/table
1245 \row \li \c page-break-after
1246 \li [ auto | always ]
1247 \li Make it possible to enforce a page break after the paragraph/table
1248 \row \li \c float
1249 \li [ left | right | none ]
1250 \li Specifies where an image or a text will be placed in another element. Note that the \c float property is
1251 only supported for tables and images.
1252 \row \li \c text-transform
1253 \li [ uppercase | lowercase ]
1254 \li Select the transformation that will be performed on the text prior to displaying it.
1255 \row \li \c font-kerning
1256 \li [ normal | none ]
1257 \li Enables or disables kerning between text characters.
1258 \row \li \c font-variant
1259 \li small-caps
1260 \li Perform the smallcaps transformation on the text prior to displaying it.
1261 \row \li \c word-spacing
1262 \li <width>px
1263 \li Specifies an alternate spacing between each word.
1264 \row \li \c line-height
1265 \li <number>[% | px | pt | cm]
1266 \li Specifies the height of a line. It can be one of the
1267 following:
1268 \list
1269 \li fixed line height in pixels, points, or centimeters.
1270 \li a percentage of the current font size.
1271 \endlist
1272 \endtable
1273
1274 \note Certain CSS properties are only supported when applied to a block tag, such as \c{<p>}.
1275 Setting these properties on a \c{<span>}, for instance, will have no effect. The margin is one
1276 example of such a property. See QTextBlockFormat and QTextCharFormat for an overview of the
1277 formatting options available on blocks and spans in QTextDocument.
1278
1279 \section1 Qt-specific CSS properties
1280
1281 Besides the standard CSS properties listed earlier, the following
1282 Qt-specific properties can also be used to style a text block:
1283
1284 \table
1285 \header \li Property
1286 \li Values
1287 \li Description
1288 \row
1289 \li \c -qt-block-indent
1290 \li \c <number>
1291 \li Indents the text block by the specified no. spaces.
1292 \row
1293 \li \c -qt-list-indent
1294 \li \c <number>
1295 \li Indents the list items by the specified no. of spaces.
1296 \row
1297 \li \c -qt-list-number-prefix
1298 \li \c <string>
1299 \li Prefixes the given string to list number in an HTML ordered list.
1300 \row
1301 \li \c -qt-list-number-suffix
1302 \li <string>
1303 \li Suffixes the given string to list number in an HTML ordered list.
1304 \row
1305 \li \c -qt-paragraph-type
1306 \li \c empty
1307 \li Hides the text block.
1308 \row
1309 \li \c -qt-table-type
1310 \li \c{root | frame}
1311 \li \c root renders the text blocks inline without borders and
1312 indentation, whereas \c frame renders them on a new line
1313 with a frame around.
1314 \row
1315 \li \c -qt-user-state
1316 \li \c <number>
1317 \li Adds it as user data for the text block.
1318 \endtable
1319
1320 \section1 Supported CSS Selectors
1321
1322 All CSS 2.1 selector classes are supported except pseudo-class selectors such
1323 as \c{:first-child}, \c{:visited} and \c{:hover}.
1324
1325*/