获取 QLabel 的矩形宽度
Posted
技术标签:
【中文标题】获取 QLabel 的矩形宽度【英文标题】:Get QLabel's rectangle width 【发布时间】:2021-06-20 09:26:22 【问题描述】:我有以下代码:
QLabel *la = new QLabel(ui->lineEdit->text());
la->setStyleSheet("background-color : #4682b4; color: white; font-size: 25px; padding: 8%;");
int w = la->fontMetrics().boundingRect(la->text()).width();
问题是我无法调整 QLabel 的正确宽度。 w
没有考虑使用 setStyleSheet() 所做的更改。我需要获取文本所在矩形的宽度。我该怎么做?
【问题讨论】:
试试:la->adjustSize();
int w = la->sizeHint().width();
【参考方案1】:
大小更新于paintEvent
,您可以使用零计时器获取大小。
la->setStyleSheet("background-color : #4682b4; color: white; font-size: 25px; padding: 8%;");
QTimer::singleShot(0,[=]()
int w = la->fontMetrics().boundingRect(la->text()).width();
);
或者您可以调用qApp->processEvents();
手动旋转事件循环。
la->setStyleSheet("background-color : #4682b4; color: white; font-size: 25px; padding: 8%;");
qApp->processEvents();
int w = la->fontMetrics().boundingRect(la->text()).width();
【讨论】:
以上是关于获取 QLabel 的矩形宽度的主要内容,如果未能解决你的问题,请参考以下文章