2

有没有办法在 Qt 5 中绘制小​​数点大小的文本。我正在尝试使用QFont::setPointSizeF(),但它似乎不适用于我尝试过的任何平台(mac/linux/windows),并且点大小总是四舍五入。

QFontDatabase::isScalable并在所有情况下QFontDatabase::isSmoothlyScalable返回true字体。

我尝试设置各种QFont::fontHintingPreferenceQPainter::RenderHint.

我也许可以使用QFont::setPixelSizeand来解决这个问题QPainter::scale,但看起来很奇怪,QFont::setPointSizeF它坏了?!

我错过了什么或做错了什么?

显示问题的简单程序:

#include <QtWidgets>

class MyWidget : public QWidget
{
public:
    MyWidget() : QWidget(0)
    {
    }

protected:
    void paintEvent(QPaintEvent */*e*/)
    {
        QPainter p(this);
        int y=10;

        for (qreal i = 10; i < 20; i += 0.2) {
            QFont font("Times"); // or any font font in the system
            font.setPointSizeF(i);
            p.setFont(font);
            p.drawText(1, y, QString("This should be point size %1 but is %2!").arg(font.pointSizeF()).arg(QFontInfo(font).pointSizeF()));
            y += i;
        }
    }
};

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    MyWidget widget;
    widget.resize(400, 740);
    widget.show();
    return app.exec();
}
4

2 回答 2

1

这不是意外的行为。请参阅下面的行:

"This should be point size 10 but is 9.75!"
"This should be point size 10.2 but is 10.5!"
"This should be point size 10.4 but is 10.5!"
"This should be point size 10.6 but is 10.5!"
"This should be point size 10.8 but is 10.5!"
"This should be point size 11 but is 11.25!"
"This should be point size 11.2 but is 11.25!"
"This should be point size 11.4 but is 11.25!"
"This should be point size 11.6 but is 11.25!"
"This should be point size 11.8 but is 12!"
"This should be point size 12 but is 12!"
"This should be point size 12.2 but is 12!"
...

然后,还要检查文档:

Sets the point size to pointSize. The point size must be greater than zero. The requested precision may not be achieved on all platforms.

于 2013-09-26T19:43:17.990 回答
0

似乎 Qt 根据点大小计算像素大小,最终以 QFont::setPixelSize 为参数,它以 int 作为参数,因此它被舍入(或类似的东西)。

因此,为了获得更好的精度,我可以执行以下操作:

void paintEvent(QPaintEvent * /*e*/)
{
    QPainter p(this);
    int y=10;

    for (qreal i = 10; i < 20; i += 0.2) {
        QFont font("Times"); // or any font
        font.setPointSizeF(i); // this has round to int error (on 72 dpi screen 10.2 would be rounded to 10 and 10.6 to 11.0 etc)
        p.setFont(font);

        qreal piX = i * p.device()->logicalDpiX() / 72.0;
        qreal piY = i * p.device()->logicalDpiY() / 72.0;
        qreal xscale = piX / qRound(piX);
        qreal yscale = piY / qRound(piY);

        //p.save();
        p.translate(1, y);
        p.scale(xscale, yscale);
        p.drawText(0, 0, QString("This should be point size %1 but is %2!").arg(font.pointSizeF()).arg(QFontInfo(font).pointSizeF() * xscale));
        p.resetTransform();
        //p.restore();
        y += i;
    }
}

我可以通过这种方式得到想要的结果。

于 2013-09-26T22:47:26.853 回答