QTextObjectInterface Class
QTextObjectInterface 类允许在QTextDocument中绘制自定义文本对象。更多内容...
| 头文件: | #include <QTextObjectInterface> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Gui) target_link_libraries(mytarget PRIVATE Qt6::Gui) |
| qmake: | QT += gui |
公共函数
| virtual | ~QTextObjectInterface() |
| virtual void | drawObject(QPainter *painter, const QRectF &rect, QTextDocument *doc, int posInDocument, const QTextFormat &format) = 0 |
| virtual QSizeF | intrinsicSize(QTextDocument *doc, int posInDocument, const QTextFormat &format) = 0 |
详细说明
文本对象描述了文本文档中一个或多个元素的结构;例如,从 HTML 导入的图像就是通过文本对象实现的。在渲染文档时,文本对象知道如何布局和绘制其元素。
Qt 允许通过将自定义object type 注册到QTextCharFormat 来将自定义文本对象插入文档。该类型还必须实现QTextObjectInterface,并与文档的QAbstractTextDocumentLayout 保持registered 。在渲染QTextDocument 时遇到该对象类型时,将调用该接口的intrinsicSize()和drawObject()函数。
以下列表说明了将自定义文本对象插入文档所需的步骤:
- 选择一个objectType 。objectType 是一个整数,其值大于或等于QTextFormat::UserObject 。
- 创建一个QTextCharFormat 对象,并使用setObjectType()函数将对象类型设置为所选类型。
- 实现 QTextObjectInterface 类。
- 调用QAbstractTextDocumentLayout::registerHandler() 并传入您的 QTextObjectInterface 子类的实例,以注册您的对象类型。
- 将带有上述所选对象类型的QTextCharFormat 的QChar::ObjectReplacementCharacter 插入到文档中。如前所述,每当遇到替换字符时,系统就会以QTextFormat 作为参数调用 QTextObjectInterface 的intrinsicSize() 和drawObject() 函数。
实现文本对象的类需要同时继承QObject 和 QTextObjectInterface。QObject 必须是第一个被继承的类。例如:
class SvgTextObject : public QObject, public QTextObjectInterface
{
Q_OBJECT
Q_INTERFACES(QTextObjectInterface)文本对象的数据通常通过QTextCharFormat::setProperty() 存储在QTextCharFormat 中,然后使用QTextCharFormat::property() 进行检索。
警告:复制 和粘贴操作会忽略自定义文本对象。
另请参阅 QTextCharFormat 和QTextLayout 。
成员函数文档
[virtual noexcept] QTextObjectInterface::~QTextObjectInterface()
删除此链接:QTextObjectInterface 。
[pure virtual] void QTextObjectInterface::drawObject(QPainter *painter, const QRectF &rect, QTextDocument *doc, int posInDocument, const QTextFormat &format)
使用指定的painter 绘制此文本对象。
要绘制的矩形rect 的大小,是先前由intrinsicSize()计算得出的。该矩形的位置是相对于painter 的。
您还可以获取该文档(doc )以及该文档中format 的位置(posInDocument )。
另请参阅 intrinsicSize()。
[pure virtual] QSizeF QTextObjectInterface::intrinsicSize(QTextDocument *doc, int posInDocument, const QTextFormat &format)
intrinsicSize() 函数返回由format 表示的文本对象在给定文档(doc )中给定位置(posInDocument )处的大小。
计算出的尺寸将用于后续对该format 的drawObject() 调用。
另请参阅 drawObject()。
© 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.