How to get font of widget in Qt set by stylesheet?

折月煮酒 提交于 2019-12-01 18:58:28

To load values from Qt Stylesheet you should call this methods:

widget->style()->unpolish(widget);
widget->style()->polish(widget);
widget->update();

After this all values of your widget will be updated according your stylesheet values specified.

You can retrieve a font of a specific widget reading it's properties, as the following:

//Get pushbutton font.
QFont font = ui->pushButton->property("font").value<QFont>();
qDebug() << font.family() << font.pointSize();

//Get MainWindow font.
QFont font2 = property("font").value<QFont>();
qDebug() << font2.family() << font2.pointSize();

The best I can tell from QStyleSheetStyle::updateStyleSheetFont, the widget always contains the resolved font from the stylesheet. I'd expect QWidget::font() to return the resolved font that you've set using the stylesheet - i.e. the font that is the merged application font, any parent widget fonts, and the stylesheet font.

The widget must be polished first, of course, unless you're querying after the events have been delivered (i.e. from within the event loop).

// https://github.com/KubaO/stackoverflown/tree/master/questions/style-font-query-test-45422885
#include <QtWidgets>

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QLabel label("Test");
   auto font1 = label.font();
   label.setStyleSheet("font-size: 49pt;");
   label.show();
   label.ensurePolished();
   auto font2 = label.font();
   Q_ASSERT(font1.pointSize() != 49);
   Q_ASSERT(font2.pointSize() == 49);
   Q_ASSERT(font1.family() == font2.family());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!