简体   繁体   中英

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

I have Qt application with custom stylesheet applied to it (and for all widgets in general) with custom font included in this stylesheet. But when try to get font of some widget font() method return different font. I want to get the font of a QWidget which is set by a stylesheet. The font() method always returns the global system font or the font set by setFont() , but not the font which is set by setStyleSheet() and is used for painting in the widget. I need the font to do some calculations based on the font size. I use Qt 4.6. How can I get real font of widget (that is showing when application run) set by stylesheet?

After some investigations I saw that if I apply defined stylesheet to some widget I can get proper font information (defined by stylesheet) with myWidget->font() method. Also when I set stylesheet to whole MainWindow I can get proper font information with font() method for all the widgets that MainWindow contains. But, when I set stylesheet to instance of QApplication the font() method for all the widgets return default font or the font previously set by setFont() . Why so?

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();

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.

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 - ie 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 (ie 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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM