View Full Version : QTextEdit::setHtml(): how can I pass a string with an embedded image?

21st June 2009, 16:46
is it possibile to pass to setHtml() a string with a self-contained image? I know I can do the following:

QString html;
html.append("<img src=\"c:\\temp\\sample.png\">");

and it works. However, I would like to get rid of the external image file (I am generating it at runtime).

My first attempt was to build the html incrementally by repeteadly calling QTextEdit::insertHtml() and QTextEdit::insertImage(), but that messes things up. I guess that's because I am generating the html by recursion (visiting a tree), so the "start" and "end" tags are usually separated by many calls to "insertHtml()", and formatting gets lost in the way.

I also tried to encode the images in the html using some "base64" encoding snippet found on the net, but it doesn't work.


Qt 4.5.1, Vista Sp1, VS Express 2008

21st June 2009, 18:03
Ooops, I must be stupid: the base64 approach works fine. I probably messed up something on my first attempt.

21st June 2009, 18:12
No, it doesn't work. It was just a placeholder image displayed by QTextEdit, not the actual image. The question is still open.

21st June 2009, 18:24
Years ago I write an article at the wiki. This my be a startpoint for you to integrate images into your QTextEdit. http://wiki.qtcentre.org/index.php?title=QTextBrowser_with_images_and_CSS (http://wiki.qtcentre.org/index.php?title=QTextBrowser_with_images_and_CSS)

P.s.: Don't know if it still works with 4.5...

21st June 2009, 19:06
Thank you Lykurg,
it works pretty well! Here is the working code for future reference:

QString html;

QImage img("c:\\temp\\sample.png"); // todo: generate image in memory
myTextEdit->document()->addResource(QTextDocument::ImageResource, QUrl("sample.png" ), img);

html.append("<p><img src=\":sample.png\"></p>");