有没有办法在html中插入QPixmap对象?

Pie*_*esu 5 html qt qpixmap

简单的情况:我有一个对象,它有一个QPixmap成员.首先创建对象(pixmap现在为null),然后pixmap从数据库中获取并插入到对象中.我需要在html代码()中插入pixmap并在h中显示html代码,QLabel但我不知道如何制作它,因为pixmap的路径未知.

我知道如何从资源文件和硬盘上的文件插入图像,但事实并非如此.我QMimeSourceFactory在qt 3.3.4上使用了类,但是在4.6.2上它被弃用了.助理说:"改用资源系统".但资源系统使用app编译,但需要在运行时读取图像.

我将不胜感激任何帮助.谢谢.

hmu*_*ner 11

如果您只想在QLabel中显示QPixmap,则应使用QLabel :: setPixmap.您可以使用QPixmap :: loadFromData在内存中构建像素映射.

如果要在HTML中显示内存像素图,例如在QWebView中,则可以使用

    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    pixmap.save(&buffer, "PNG");
    QString url = QString("<img src=\"data:image/png;base64,") + byteArray.toBase64() + "\"/>";
Run Code Online (Sandbox Code Playgroud)

(另)

QLabel :: setText不适用于HTML,但使用富文本格式.我不知道Qt富文本实现是否支持数据:协议.

将pixmap插入QWebView的另一种方法是使用QNetworkAccessManager的子类并重新实现其createRequest()函数以使用您自己的协议("myprot:")检查URL并在其中插入像素图数据.但这看起来有点矫枉过正.


hmu*_*ner 5

我将其放在另一个答案中,以便能够格式化代码。我编写了以下程序,它可以按预期工作:

#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWidget window;
    window.resize(320, 240);
    window.show();
    window.setWindowTitle(
        QApplication::translate("toplevel", "Top-level widget"));
    QLabel* label = new QLabel(&window);
    label->setTextFormat(Qt::RichText);
    QString text = "<html><h1>Test</h1>here is an image: ";
    QPixmap pixmap("testicon.jpg");
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    pixmap.save(&buffer, "PNG");
    QString url = QString("<img src=\"data:image/png;base64,") + byteArray.toBase64() + "\"/>";
    text += url;
    text += "</html>";
    label->setText(text);

    label->move(100, 100);
    label->show();
    return app.exec();
}
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 3

我知道这是一个老问题,但这是另一种选择。

我对 中的图像也有类似的问题QToolTip。我可以很好地引用磁盘中的图像,但默认的缩放行为不平滑并且看起来很糟糕。我重新实现了自己的工具提示类并使用了自定义QTextDocument类,以便我可以覆盖QTextDocument::loadResource().

对于您的情况,您可以在 src 属性中指定关键字img。然后在您的实现中loadResource()返回用关键字标识的 QPixmap。

这是基本代码(在此上下文中未经测试):

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);
  }
};
Run Code Online (Sandbox Code Playgroud)