【问题标题】:Get QLabel's rectangle width获取 QLabel 的矩形宽度
【发布时间】: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();

标签: c++ qt qlabel


【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 2021-01-10
    • 2017-03-15
    • 2021-07-14
    • 2021-08-27
    • 2016-09-29
    相关资源
    最近更新 更多