Qt:包装文字的heightForWidth

时间:2012-04-06 10:48:06

标签: c++ qt fonts

我有一个宽度不一的文字框和一个自动换行的文字。每次用户更改框的宽度时,我都需要设置新的高度。 QPainter在 paintEvent(QPaintEvent *)函数中显示该框。有几种解决方案,例如当前(不是很聪明,我在 resizeEvent(QResizeEvent *)中执行此操作):

unsigned new_height = 0; // the height i want to find out.
unsigned given_width = width();
QPainter painter (this); // i need painter, because i want to ask it's default font.
QLabel lab;              // the widget that can do word-wrap.
lab.setText( "A word wrapped text" ); // the text
lab.setFont( painter.font() );        // set QPainter's default font.
lab.setWordWrap( true );              // enable word-wrap
new_height = lab.heightForWidth( given_width ); // tada! :)

但是代码太过分了:
1)在paintEvent(QPaintEvent *)之外创建QPainter并不好;
2)但是我需要QPainter来请求它的默认字体,以询问该字体的指标。

我应该更改我的代码并在 paintEvent(QPaintEvent *)函数内的QPainter::boundingRect()帮助下执行此操作吗?但我想减少 paintEvent(QPaintEvent *)中的CPU消耗,并仅在宽度改变时计算新高度,但不是每次显示时都计算。

针对主题目的的其他解决方案是什么? QFontMectircs?

1 个答案:

答案 0 :(得分:1)

我认为你有正确的想法使用QFontMetrics。课堂的整个想法是帮助你在这里的情况。看看QFontMetricsF::boundingRect()

使用目标绘制矩形作为输入矩形,但将高度设置为窗口小部件高度的最大值。我只是想把INT_MAX这样的东西放在里面。 :)

相关问题