0

我认为问题仅在于 QTextDocument 对非标准字体的管理。尽管如此,我还是会概述一下我在做什么,以防我忽略了其余代码中的某些内容。

我正在尝试打印富文本(使用 qt 支持的 html 标签格式化的文本)和图像的混合。输出可以是 PDF 或物理打印输出。

我使用 QImage 和 QTextDocument 创建图像和文本,然后使用 QPainter 和 QPrinter 以连贯的 PDF、xps 或打印输出实际打印出结果。该应用程序在 Windows 7/8 下运行。

我需要将字体更改为非标准字体;就我而言,Myriad Pro Light 和 Myriad Pro Semibold。这些字体默认情况下不存在于 Windows 上,因此我需要先为机器或应用程序安装它们。

代码去掉了最不相关的部分,看起来像:

void MyClass::print(QPrinter* printer, MyPrintingSettings settings, QString myRichText)
{
    // load my fancy font
    QString fontPath = "MyriadPro-Light.otf";
    if(!QFile(fontPath).exists() ||
      (QFontDatabase::addApplicationFont(fontPath) == -1))
    {
         //this does not happen.
         qDebug() << "could not load font " << fontPath << " :-(\n";
         return;
    }

    // Set the painter and printer for accurate printing of both text
    // and images, with correct re-scaling, regardless of user-selected
    // printer properties.
    printer->pageRect().moveTo(0,0);        
    QPainter m_painter(printer);
    setWindowSize(settings);
    setPrintedRectangle(settings);

    //set the default font for the painter.
    QFont font;
    font.setFamily("Myriad Pro Light");
    font.setPointSize(settings.defaultFontSize);
    m_painter.setFont(font);

    //Create a document for printing. 
    QTextDocument document;
    document.documentLayout()->setPaintDevice(printer);
    document.setDefaultFont(font);
    document.setDocumentMargin(0.0);

    // I believe this is where the font fails to be correctly used.
    document.setHtml(myRichText);

    //drawing/printing.
    document.drawContents(&m_painter);
    m_painter.end();
}

观察到的输出取决于确切的富文本字符串:

  • 对于像:这样的字符串QString myRichText = "my text",正确使用了默认字体。这不是一个令人满意的解决方案,因为我需要更改富文本字符串中的字体。

  • 对于像:这样的字符串QString myRichText = "<span style="font-family:Myriad Pro Light;">my text</span>,字体使用不正确(使用了 tahoma)。

  • 在机器上“手动”安装字体不会改变任何东西。

  • 奖励问题:我不知道这是否是一个相关问题。如果我在“Myriad Pro Light”之外安装“Myriad Pro Semibold”,无论是手动安装整个机器还是通过 QtApplication 的代码,两者之间似乎存在名称混淆:始终使用 Semibold 而不是 light,和<b>标签导致切换到粗体 tahoma。

所以,长话短说:我如何让 QTextDocument 正确设置文本的花哨的非标准字体,基于富文本?

4

1 回答 1

0

啊。问题只是富文本。

使用这个:

QString myRichText = "<span style="font-family:'Myriad Pro Light';">my text</span>

...工作得更好。

使用这个:

QString myRichText = "<span style="font-family:'Myriad Pro Light' font-weight=100;">my <b>text</b></span>

...还解决了“轻”和“半粗体”之间的名称混淆。

感谢所有对此进行调查的人。

于 2013-08-20T13:25:10.317 回答