常见的富文本编辑任务
开发人员在使用 Qt 编辑和处理文本文档时,通常会执行多项任务。其中包括使用QTextBrowser 和QTextEdit 等显示控件,使用QTextDocument 创建文档,使用QTextCursor 进行编辑,以及导出文档结构。 本文概述了使用富文本类完成这些任务的一些常用方法,并展示了可在您自己的应用程序中重复使用的便捷模式。
使用 QTextEdit
可以通过以下方式创建并使用文本编辑器控件来显示 HTML:
QTextEdit *editor = new QTextEdit(parent);
editor->setHtml(aStringContainingHTMLtext);
editor->show();默认情况下,文本编辑器包含一个带有根框架的文档,其中包含一个空文本块。应用程序可以获取该文档以便直接对其进行修改:
QTextDocument *document = editor->document();文本编辑器的光标也可用于编辑文档:
QTextCursor cursor = editor->textCursor();尽管一个文档可以同时使用多个光标进行编辑,但QTextEdit 每次只显示一个光标。因此,如果我们要更新编辑器以显示特定的光标或其选定内容,则需要在修改文档后设置编辑器光标:
editor->setTextCursor(cursor);选择文本
通过类似用户在文本编辑器中执行的操作来移动光标,即可选中文本。 要选中文档中两点之间的文本,我们需要将光标定位在第一点,然后使用特殊模式(QTextCursor::MoveMode )配合移动操作(QTextCursor::MoveOperation )来移动光标。选中文本时,我们会将选区锚点保留在原光标位置,这与用户在选文时按住Shift键的行为一致:
cursor.movePosition(QTextCursor::StartOfWord);
cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);在上方的代码中,通过此方法选中了一个完整的单词。QTextCursor 提供了多种常见的移动操作,用于选择单个字符、单词、行以及整个块。
查找文本
QTextDocument 提供了一个基于光标的搜索界面,便于像使用文本编辑器那样查找和修改文本。以下代码查找文档中某个特定单词的所有实例,并更改每个实例的颜色:
QTextCursor newCursor(document);
while (!newCursor.isNull() && !newCursor.atEnd()) {
newCursor = document->find(searchString, newCursor);
if (!newCursor.isNull()) {
newCursor.movePosition(QTextCursor::WordRight,
QTextCursor::KeepAnchor);
newCursor.mergeCharFormat(colorFormat);
}
}请注意,每次搜索和替换操作后,光标无需移动;它始终位于刚刚被替换的单词末尾。
打印文档
QTextEdit 该功能专为在屏幕上阅读的大型富文本文档而设计,其渲染方式与网页浏览器相同。因此,它不会自动将文档内容分割成适合打印的页面大小的块。
QTextDocument 提供了print()函数,允许使用QPrinter 类打印文档。以下代码演示了如何在QTextEdit 中准备文档,以便使用QPrinter 进行打印:
QTextDocument *document = editor->document();
QPrinter printer;
QPrintDialog *dlg = new QPrintDialog(&printer, this);
if (dlg->exec() != QDialog::Accepted)
return;
document->print(&printer);从文本编辑器获取文档,然后创建一个 `QPrinter ` 并使用 `QPrintDialog` 进行配置。如果用户接受打印机的配置,则使用 `print()` 函数对文档进行格式化并打印。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.