PDA

View Full Version : Insert QPixmap in QTextDocument



guidupas
25th March 2014, 18:41
Hello guys!

I need to insert a QPixmap in a QTextDocument and all I tried didnt work.

If anyone could help me. Code below:



QPrinter impressora(QPrinter::HighResolution);
QTextDocument document;
document.setHtml(html);
if(matriz == true)
{
QPainter painter;

QPalette palette;

QRect rectpag = impressora.pageRect();

palette.setColor(backgroundRole(), QColor(255, 255, 255));
this->ui->tab_3->setPalette(palette);
this->ui->tab_3->setAutoFillBackground(true);

QPixmap pm = this->ui->tab_3->grab();
pm = pm.transformed(QTransform().rotate(270));
QSize tamanho = pm.size();

tamanho.scale(rectpag.size(), Qt::KeepAspectRatio);

painter.drawPixmap(Qt::AlignCenter, Qt::AlignHCenter, tamanho.width(), tamanho.height(), pm);

document.drawContents(&painter);
this->ui->tab_3->setAutoFillBackground(false);
}
document.print(&impressora);


Thanks a lot.

ChrisW67
26th March 2014, 02:33
Your code never tries to insert an image into a QTextDocument. Inserting an image is done with QTextCursor::insertImage() and a suitable QTextImageFormat that names an image resource that has been added using QTextDocument::addResource(). The last link shows an example of this process.

I have not tried it, but I expect that calling QTextDocument::setHtml() with HTML that references an accessible image through an img element should also work.


What your code does is try to paint an image onto a QPainter that is not associated with a paint device (through the constructor or QPainter::begin()). You then draw the contents of the QTextDocument into the same uninitialised painter. When you finally call QTextDocument::print() the document is unchanged and image free.

guidupas
26th March 2014, 12:18
Thank you for the reply ChrisW67. But I need to insert an image that in not saved in the HD. I can create an image from the Qpixmap and even doing that it will not be in my HD. Can I insert that image with QTextCursor?

ChrisW67
27th March 2014, 00:09
Yes, exactly as in the example QTextDocument::addResource() example I linked to before. The URL is just a unique identifier, it does not have to point at a web or file resource.

guidupas
27th March 2014, 13:13
Thanks ChrisW67. It worked. Code below:


QPrinter impressora(QPrinter::HighResolution);

QTextDocument document;
document.setHtml(html);
if(matriz == true)
{
QTextCursor cursor(&document);

QPalette palette;

palette.setColor(backgroundRole(), QColor(255, 255, 255));
this->ui->tab_3->setPalette(palette);
this->ui->tab_3->setAutoFillBackground(true);

QPixmap pm = this->ui->tab_3->grab();
pm = pm.transformed(QTransform().rotate(270));

cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);

QImage img = pm.toImage();
img = img.scaledToHeight(img.height()-60);
cursor.insertImage(img);

this->ui->tab_3->setAutoFillBackground(false);
}

document.print(&impressora);