PDA

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



mattc
21st June 2009, 15:46
Hello,
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\">");
myTextEdit->setHtml(html);

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.

Thanks

Qt 4.5.1, Vista Sp1, VS Express 2008

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

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

Lykurg
21st June 2009, 17: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...

mattc
21st June 2009, 18: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>");

myTextEdit->setHtml(html);