有没有办法在Qt 5中绘制小数点大小的文本。
我正在尝试使用QFont::setPointSizeF()
,但它似乎不适用于我试过的任何平台(mac / linux / windows),并且点大小总是四舍五入。
QFontDatabase::isScalable
和QFontDatabase::isSmoothlyScalable
都会返回true
字体。
我尝试设置各种QFont::fontHintingPreference
和QPainter::RenderHint
。
我或许可以使用QFont::setPixelSize
和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();
}
答案 0 :(得分: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.
答案 1 :(得分: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;
}
}
我可以通过这种方式获得理想的结果。