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

Vasyl picture Vasyl · Feb 24, 2015 · Viewed 7.7k times · Source

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?

Answer

Antonio Dias picture Antonio Dias · Feb 25, 2015

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