Important: Please read the Qt Code of Conduct -

QPixmap: How to render?

  • Hello,

    i want to render a qt chart to a pixmap which i want to insert into a qtextdedit.

        QPixmap renderedPix;
        m_chartView->render(&renderedPix, QRectF(), QRect(), Qt::IgnoreAspectRatio);
        QPixmap renderedPix;

    Both code examples won't work.
    And: How can i insert this rendered Pixmap into QTextEdit?

    Thank you,

  • Lifetime Qt Champion

    What does not work? How did you check?

    To insert image see documentation (

    void TextEdit::insertFromMimeData( const QMimeData *source )
        if (source->hasImage())
            QImage image = qvariant_cast<QImage>(source->imageData());
            QTextCursor cursor = this->textCursor();
            QTextDocument *document = this->document();
            document->addResource(QTextDocument::ImageResource, QUrl("image"), image);

  • Moderators

    @HenrikSt. said:

    Both code examples won't work.

    you need to create the pixmap with a given size. Currently you are creating a null-pixmap.

    And: How can i insert this rendered Pixmap into QTextEdit?

    QUrl url("mydata://image1");
    QTextDocument *document = textEdit->document();
    document->addResource(QTextDocument::ImageResource, url, QVariant::fromValue<QPixmap>(pix));
    QTextCursor cursor = textEdit->textCursor();
    QTextImageFormat imageFormat;
    imageFormat.setWidth( image.width() );
    imageFormat.setHeight( image.height() );
    imageFormat.setName( url.toString() );
    // or alternatively:
    QTextDocumentFragment fragment = QTextDocumentFragment::fromHtml("<img src='mydata://image1'>");

  • Lifetime Qt Champion

    @HenrikSt. Maybe you should resize the QPixmap like in the example in the documentation (

    QPixmap pixmap(m_chartView->size());

  • @raven-worx
    Thanks for your answer.

    How can create a pixmap with a given size?
    Can you make an example?

    Thanks :)

  • The QPixmap class has a constructor that takes a QSize parameter and therefore allows you to create a pixmap of a given size. That is what @jsulm is doing in the first line of his last code example. Documentation.