QPrinter生成PDF时QTextFrame内容异常,仅显示黑块求助
QTextFrame边框在PDF中显示异常的解决方法
我看你遇到了个挺头疼的问题:用QPrinter生成PDF时,QTextFrame的显示效果和QTextEdit里完全不一样——PDF里只显示一条黑线,看不到文本,但QTextEdit里的效果却是你想要的。先看看你写的代码:
#include <QPainter> #include <QTextFrameFormat> #include <QTextCursor> #include <QTextFrame> #include <QTextEdit> #include <QPrinter> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextDocument doc; QPixmap map(1024, 1024); map.fill(Qt::white); QPainter p; p.begin(&map); p.fillRect(QRect(0,0, 4, map.height()), QBrush(Qt::red)); p.end(); QTextFrameFormat frameFormat; QBrush bruh(map); bruh.setColor(Qt::transparent); frameFormat.setBackground(bruh); frameFormat.setPadding(6); auto cur = new QTextCursor(&doc); auto frame = cur->insertFrame(frameFormat); auto curf = new QTextCursor(frame); curf->insertText("Hello this is qt program!"); QPrinter pdf; pdf.setOutputFileName("E:\test.pdf"); pdf.setOutputFormat(QPrinter::PdfFormat); doc.print(&pdf); QTextEdit edt; edt.setDocument(&doc); edt.show(); return a.exec(); }
问题原因分析
这里有两个关键问题导致了显示和打印的不一致:
- QPixmap背景画刷的打印兼容性:QPrinter的PDF打印后端对用QPixmap创建的背景画刷支持很差,尤其是你还设置了
bruh.setColor(Qt::transparent),这会让打印时的画刷渲染异常,直接覆盖了文本内容。 - 文件路径的转义错误:
"E:\test.pdf"里的\t会被解析为制表符,实际保存的路径是错的——虽然这不是看不到文本的直接原因,但也是必须修正的问题。
解决方法
我们换一种更原生的方式实现边框效果,直接用QTextFrameFormat自带的边框属性,这样能保证显示和打印的逻辑完全一致:
#include <QPainter> #include <QTextFrameFormat> #include <QTextCursor> #include <QTextFrame> #include <QTextEdit> #include <QPrinter> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextDocument doc; // 用QTextFrameFormat原生属性设置边框,替代QPixmap背景的方式 QTextFrameFormat frameFormat; // 设置边框宽度和颜色 frameFormat.setBorder(4); frameFormat.setBorderBrush(Qt::red); // 保留你需要的内边距 frameFormat.setPadding(6); // 可选:设置背景色 frameFormat.setBackground(Qt::white); auto cur = new QTextCursor(&doc); auto frame = cur->insertFrame(frameFormat); auto curf = new QTextCursor(frame); curf->insertText("Hello this is qt program!"); QPrinter pdf; // 修正路径转义:用双反斜杠或者正斜杠 pdf.setOutputFileName("E:\\test.pdf"); pdf.setOutputFormat(QPrinter::PdfFormat); doc.print(&pdf); QTextEdit edt; edt.setDocument(&doc); edt.show(); return a.exec(); }
为什么这个方法有效?
QTextFrameFormat本身就提供了setBorder()和setBorderBrush()来设置边框,这是Qt文本框架原生支持的属性,不管是在QTextEdit里显示还是用QPrinter打印,渲染逻辑都是统一的,不会出现兼容性问题。
另外,记得把文件路径里的单反斜杠改成双反斜杠\\,或者直接用正斜杠/,避免转义字符导致的路径错误。
内容的提问来源于stack exchange,提问作者unknown.prince
相关产品推荐
相关产品推荐

