对于Qt 4.6.x,如何自动调整文本大小以适合指定的宽度? [英] For Qt 4.6.x, how to auto-size text to fit in a specified width?

查看:158
本文介绍了对于Qt 4.6.x,如何自动调整文本大小以适合指定的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的QGraphicsRectItem :: paint()里面,我试图在rect()内绘制项目的名称.但是,对于每个不同的项目,它们可以具有可变的宽度,类似地,名称也可以具有可变的长度.

Inside of my QGraphicsRectItem::paint(), I am trying to draw the name of the item within its rect(). However, for each of the different items, they can be of variable width and similarly names can be of variable length.

当前,我从最大字体大小开始,检查它是否适合并递减直到找到适合的字体大小.到目前为止,我还没有找到一种快速简便的方法来做到这一点.有没有更好或更有效的方法?

Currently I am starting with a maximum font size, checking if it fits and decrementing it until I find a font size that fits. So far, I haven't been able to find a quick and easy way to do this. Is there a better, or more efficient way to do this?

谢谢!

void checkFontSize(QPainter *painter, const QString& name) {
 // check the font size - need a better algorithm... this could take awhile
 while (painter->fontMetrics().width(name) > rect().width()) {
  int newsize = painter->font().pointSize() - 1;
  painter->setFont(QFont(painter->font().family(), newsize));
 }
}

推荐答案

qtcentre.org的Johannes提供了以下解决方案:

Johannes from qtcentre.org offered the following solution:

float factor = rect().width() / painter->fontMetrics().width(name);
 if ((factor < 1) || (factor > 1.25))
 {
  QFont f = painter->font();
  f.setPointSizeF(f.pointSizeF()*factor);
  painter->setFont(f);
 }

我在程序中进行了尝试,到目前为止,它似乎运行良好.我喜欢它,因为它可以一次生成结果,但是它假定字体宽度像其高度一样缩放.

I gave it a try in my program and so far, it seems to work quite well. I like it because it produces results in one pass, but it assumes that font width scales like its height.

http://www.qtcentre.org/threads/27839-For-Qt-4-6-x-how-to-auto-size-text-to-fit-in-指定宽度

这篇关于对于Qt 4.6.x,如何自动调整文本大小以适合指定的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆