Scaling QLabel to accommodate the contained text and nothing more

那年仲夏 提交于 2019-12-06 07:43:38

问题


I’m subclassing QLabel and inserting it into a QVBoxLayout and I’m having a problem with the size. The following screenshot is how my application currently looks:

The yellow widget on the top is my QLabel, and the layout is the default one. I’d like my label to scale down to fit the text without manually setting it with setMinimumHeight(), however that wouldn’t allow me to use strings longer than the width of the label. I’ve checked the documentation for QString (which is what I am passing to the label’s constructor) and I can’t find a way to extract the size of the text. Is there any way I can dynamically change the size of my label to fit the text, with no excess space?


回答1:


Yes you can find out the width of the text through the QFontMetrics of the QLabel. For example:

QLabel *label = new QLabel("Text");
int w = label->fontMetrics().width(label->text());
qDebug() << Q_FUNC_INFO << w;
//in my case this results in 24px, so 6px per character.


来源:https://stackoverflow.com/questions/9224960/scaling-qlabel-to-accommodate-the-contained-text-and-nothing-more

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!