From 10:00 CET Friday 22nd November we will adjust how the server works to deal with some recently reported problems. Therefore there may be a load problem, if you experience more problems than usual trying to access the forum then please PM AndyS or any of the moderators so they can inform me.


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;
        m_chartView->render(&renderedPix);
    

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

    Thank you,
    Henrik


  • Qt Champions 2018

    What does not work? How did you check?

    To insert image see documentation (http://doc.qt.io/qt-5.7/qtextedit.html):

    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);
            cursor.insertImage("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() );
    cursor.insertImage(imageFormat);
    
    // or alternatively:
    QTextDocumentFragment fragment = QTextDocumentFragment::fromHtml("<img src='mydata://image1'>");
    cursor.insertFragment(fragment);
    

  • Qt Champions 2018

    @HenrikSt. Maybe you should resize the QPixmap like in the example in the documentation (http://doc.qt.io/qt-5/qwidget.html#render):

    QPixmap pixmap(m_chartView->size());
    m_chartView->render(&pixmap);
    


  • @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.