Reputation: 10538
I am using Qt4 (I know), and have a custom widget that sets a bold font, with a point size that is 1.5 times the point size of the application font. This works without problems.
The problem now is that in case the application font size is changed, the widget's font size is not updated accordingly (as expected). My initial though was to do something along the following lines:
void MyCustomWidget::changeEvent(QEvent* e)
{
if (e->type() == QEvent::FontChange)
{
setFont(boldAndBigFont());
}
return QWidget::changeEvent(e);
}
This does not work, since the setFont()
call will trigger a FontChange
event resulting in endless calls to the change event handler. I noticed there is also ApplicationFontChange
, which is promising, however that event is not delivered to my custom widget (I verified using an event listener). Looking at the Qt code, the code responsible for propagating the ApplicationFontChange
event will only deliver this event to a few select widgets (the main window for example).
So my question is; how to solve this in a nice way? One limitation I have is that I cannot use style sheets.
My current solution leans towards a custom font change event, fired from the main window after receiving ApplicationFontChange
, but surely, I cannot be the first person to have this problem...?
Update: I found that calling QApplication::setFont(bigAndBoldFont(), "MyCustomWidget");
works as well. I do not particularly like it since I would rather keep this styling behavior tied to the implementation of the custom widget.
Upvotes: 0
Views: 692
Reputation: 12899
I can't vouch for Qt4 but the following changeEvent
implementation appears to work as expected with Qt5...
virtual void changeEvent (QEvent *event) override
{
if (event->type() == QEvent::FontChange) {
/*
* Run the default handler for the event.
*/
super::changeEvent(event);
/*
* Now get the application font and create the desired font based on
* that.
*/
auto app_font = qApp->font();
auto desired_font = QFont(app_font.family(), 1.5 * app_font.pointSize(), QFont::Bold);
/*
* If the font we now have is the desired font then fine, otherwise
* set it.
*/
if (font() != desired_font) {
setFont(desired_font);
}
event->accept();
}
super::changeEvent(event);
}
Upvotes: 1