How can I add a non-resource image to a QTextDocument ?
Answer:
You can add a non-resource image to a QTextDocument by using the internal class QTextObjectInterface for inserting custom objects into a QTextDocument. The subclass of QTextObjectInterface will result in a handler for the object you
would want to draw. Information like the name of the pixmap or geometry information is stored in the QTextFormat that you specify at QTextCursor::insertText() time and that are used as arguments to the functions of QTextObjectInterface. See the documentation:
http://doc.trolltech.com/qabstracttextdocumentlayout.html#registerHandler
http://doc.trolltech.com/qchar.html#SpecialCharacter-enum
http://doc.trolltech.com/qtextformat.html#ObjectTypes-enum
See the following example for a demonstration:
#include <QtGui>
class MyHandler : public QObject, public QTextObjectInterface
{
Q_OBJECT
Q_INTERFACES(QTextObjectInterface)
public:
MyHandler(QObject* par = 0)
: QObject(par), px("polygon.png")
{ }
QSizeF intrinsicSize(QTextDocument* doc, int posInDoc,
const QTextFormat &fmt)
{
Q_UNUSED(doc)
Q_UNUSED(posInDoc)
Q_UNUSED(fmt)
return QSizeF( px.size() );
}
void drawObject(QPainter* p, const QRectF &rect, QTextDocument* doc,
int posInDoc, const QTextFormat &fmt)
{
Q_UNUSED(doc)
Q_UNUSED(posInDoc)
Q_UNUSED(fmt)
p->drawPixmap(rect.toRect(), px );
}
private:
QPixmap px;
};
class widget : public QTextEdit
{
public:
widget(QWidget* parent = 0)
: QTextEdit(parent)
{
MyHandler* handler = new MyHandler(this);
document()->documentLayout()->registerHandler(QTextCharFormat::UserObject, handler);
QTextCharFormat fmt;
fmt.setObjectType(QTextCharFormat::UserObject);
textCursor().insertText("hello");
textCursor().insertText(QString(QChar::ObjectReplacementCharacter), fmt);
textCursor().insertText("world");
}
};
#include "main.moc"
int main(int argc, char **argv)
{
QApplication a(argc, argv);
widget w;
w.show();
return a.exec();
}