Simple situation: I have an object, which has a QPixmap
member. Object first created (pixmap is null now), then pixmap readed from data base and inserted in object. I need to insert that pixmap in html code () and display that html code in a QLabel
but I have no idea how to make it, because pixmap's path is unknown.
I know how to insert images from resource files and from files on my hard-disk, but it isn't that case. I was using QMimeSourceFactory
class on qt 3.3.4, but on 4.6.2 it is deprecated. Assistant says: "Use resource system instead". But resource system compiles with app, but it is needed to read images during runtime.
I will be grateful for any help. Thanks.
If you only want to display a QPixmap in a QLabel, you should use QLabel::setPixmap. You can construct the pixmap in memory by using QPixmap::loadFromData.
If you want to display a memory pixmap in HTML, e.g. in a QWebView, you can use
QByteArray byteArray;
QBuffer buffer(&byteArray);
pixmap.save(&buffer, "PNG");
QString url = QString("<img src=\"data:image/png;base64,") + byteArray.toBase64() + "\"/>";
(untested)
QLabel::setText does not work with HTML but with rich-text. I do not know if the data: protocol is supported by the Qt rich-text implementation.
Another way to insert a pixmap into a QWebView would be to use a subclass of QNetworkAccessManager and reimplement its createRequest() function to check for URLs with your own protocol ("myprot:") and insert the pixmap data there. But this looks like overkill.
I know this is an old question, but here is another option.
I had a similar issue with images in QToolTip
. I could reference images from disk fine, but the default scaling behavior is non-smooth and looked terrible. I reimplemented my own tooltip class and used a custom QTextDocument
class so that I could override QTextDocument::loadResource()
.
In your case, you can specify a keyword in the img
src attribute. Then in your implementation of loadResource()
return the QPixmap identified with the keyword.
Here is the basic code (untested in this context):
class MyTextDocument : public QTextDocument
{
protected:
virtual QVariant loadResource(int type, const QUrl &name)
{
QString t = name.toString();
if (t == myKeyword)
return myPixmap;
return QTextDocument::loadResource(type, name);
}
};
class MyLabel : public QFrame
{
public:
MyLabel(QWidget *parent)
: QFrame(parent)
, m_doc(new MyTextDocument(this))
{ }
virtual void paintEvent(QPaintEvent *e)
{
QStylePainter p(this);
// draw the frame if needed
// draw the contents
m_doc->drawContents(&p);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With