Search code examples
qtqt5qtextcursor

Center image inserted with QTextCursrsor::insertImage()


I'm want to print a pdf file containing some centered images. The document is created with QTextDocument and QCursor.
But i can't find a way to center (horizontally) the image in the document.

the way I insert the image is as follow :

QTextDocument previewDoc;

QTextCursor cursor(&previewDoc);

// load the picrture as resource of the document
QImage pictureImage("picture.png");
QString pictureUrl = QString("mydata://picture.png");
previewDoc.addResource(QTextDocument::ImageResource, QUrl(pictureUrl), QVariant(pictureImage));

// insert the picture in the document
cursor.insertBlock();
QTextImageFormat pictureFormat;
pictureFormat.setName(pictureUrl);
pictureFormat.setWidth(pictureImage.width()); // 150 pixelfor picture.png
cursor.insertImage(pictureFormat);

// print the document in pdf file
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFileName("output.pdf");
printer.setOutputFormat(QPrinter::PdfFormat);

printer.setPaperSize(QPrinter::A4);
printer.setResolution(300);

previewDoc.print(&printer);

Thanks


Solution

  • Try inserting a block with Alighment as HCenter and then insert the image in the block.
    For e.g.

    QTextImageFormat pictureFormat;
    pictureFormat.setName(imageURL.toString());
    
    // Insert Block
    QTextBlockFormat centerFormat;
    centerFormat.setAlignment(Qt::AlignHCenter);
    cursor->insertBlock(centerFormat);
    
    cursor->insertImage(pictureFormat);
    
    // Move to the end of document
    cursor->movePosition(QTextCursor::End);