Text Object Example¶
The Text Object example shows how to insert an SVG file into a
QTextDocument.![]()
A
QTextDocumentconsists of a hierarchy of elements, such as text blocks and frames. A text object describes the structure or format of one or more of these elements. For instance, images imported from HTML are implemented using text objects. Text objects are used by the document’slayoutto lay out and render (paint) the document. Each object knows how to paint the elements they govern, and calculates their size.To be able to insert an SVG image into a text document, we create a text object, and implement painting for that object. This object can then be
seton aQTextCharFormat. We also register the text object with the layout of the document, enabling it to drawQTextCharFormats governed by our text object. We can summarize the procedure with the following steps:
Implement the text object.
Register the text object with the layout of the text document.
Set the text object on a
QTextCharFormat.Insert a
ObjectReplacementCharacterwith that text char format into the document.The example consists of the following classes:
SvgTextObjectimplements the text object.
Windowshows aQTextEditinto which SVG images can be inserted.
SvgTextObject Class Definition¶
Let’s take a look at the header file of
SvgTextObject:class SvgTextObject(QObject, QTextObjectInterface): def __init__(self,...): super(SvgTextObject, self).__init__(...) ... public: QSizeF intrinsicSize(QTextDocument *doc, int posInDocument, const QTextFormat &format); void drawObject(QPainter *painter, const QRectF &rect, QTextDocument *doc, int posInDocument, const QTextFormat &format); };A text object is a
QObjectthat implementsQTextObjectInterface. Note that the first class inherited must beQObject, and that you must useQ_INTERFACESto let Qt know that your class implementsQTextObjectInterface.The document layout keeps a collection of text objects stored as
QObjects, each of which has an associated object type. The layout casts theQObjectfor the associated object type into theQTextObjectInterface.The
intrinsicSize()anddrawObject()functions are then used to calculate the size of the text object and draw it.
SvgTextObject Class Implementation¶
We start of by taking a look at the
intrinsicSize()function:QSizeF SvgTextObject::intrinsicSize(QTextDocument * /*doc*/, int /*posInDocument*/, const QTextFormat &format) { QImage bufferedImage = qvariant_cast<QImage>(format.property(Window::SvgData)); QSize size = bufferedImage.size(); if (size.height() > 25) size *= 25.0 / (double) size.height(); return QSizeF(size); }
intrinsicSize()is called by the layout to calculate the size of the text object. Notice that we have drawn the SVG image on aQImage. This is because SVG rendering is quite expensive. The example would lag seriously for large images if we drew them with aQSvgRenderereach time.void SvgTextObject::drawObject(QPainter *painter, const QRectF &rect, QTextDocument * /*doc*/, int /*posInDocument*/, const QTextFormat &format) { QImage bufferedImage = qvariant_cast<QImage>(format.property(Window::SvgData)); painter->drawImage(rect, bufferedImage); }In
drawObject(), we paint the SVG image using theQPainterprovided by the layout.
Window Class Definition¶
The
Windowclass is a self-contained window that has aQTextEditin which SVG images can be inserted.class Window : public QWidget { Q_OBJECT public: enum { SvgTextFormat = QTextFormat::UserObject + 1 }; enum SvgProperties { SvgData = 1 }; Window(); private slots: void insertTextObject(); private: void setupTextObject(); void setupGui(); private: QTextEdit *textEdit; QLabel *fileNameLabel; QLineEdit *fileNameLineEdit; QPushButton *insertTextObjectButton; };The
insertTextObject()slot inserts an SVG image at the current cursor position, whilesetupTextObject()creates and registers the SvgTextObject with the layout of the text edit’s document.The constructor simply calls
setupTextObject()andsetupGui(), which creates and lays out the widgets of theWindow.
Window Class Implementation¶
We will now take a closer look at the functions that are relevant to our text object, starting with the
setupTextObject()function.void Window::setupTextObject() { QObject *svgInterface = new SvgTextObject; svgInterface->setParent(this); textEdit->document()->documentLayout()->registerHandler(SvgTextFormat, svgInterface); }
SvgTextFormat‘s value is the number of our object type. It is used to identify object types by the document layout.Note that we only create one SvgTextObject instance; it will be used for all
QTextCharFormat‘s with theSvgTextFormatobject type.Let’s move on to the
insertTextObject()function:void Window::insertTextObject() { QString fileName = fileNameLineEdit->text(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::warning(this, tr("Error Opening File"), tr("Could not open '%1'").arg(fileName)); } QByteArray svgData = file.readAll();First, the
.svgfile is opened and its contents are read into thesvgDataarray.QTextCharFormat svgCharFormat; svgCharFormat.setObjectType(SvgTextFormat); QSvgRenderer renderer(svgData); QImage svgBufferImage(renderer.defaultSize(), QImage::Format_ARGB32); QPainter painter(&svgBufferImage); renderer.render(&painter, svgBufferImage.rect()); svgCharFormat.setProperty(SvgData, svgBufferImage); QTextCursor cursor = textEdit->textCursor(); cursor.insertText(QString(QChar::ObjectReplacementCharacter), svgCharFormat); textEdit->setTextCursor(cursor); }To speed things up, we buffer the SVG image in a
QImage. We usesetProperty()to store theQImagein the in theQTextCharFormat. We can retrieve it later withproperty().We insert the char format in the standard way - using a
QTextCursor. Notice that we use the specialQCharObjectReplacementCharacter.
© 2022 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.