使用QTextCursrsor :: insertImage()插入的中心图像

时间:2014-05-28 13:21:47

标签: qt qt5 qtextcursor

我想要打印包含一些居中图像的pdf文件。该文档是使用QTextDocument和QCursor创建的 但是我找不到一种方法来对文档中的图像进行居中(水平)
我插入图片的方式如下:

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);

由于

1 个答案:

答案 0 :(得分:1)

尝试插入以对齐为中心的块,然后将图像插入块中 对于例如

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);