如何在应用程序字体大小更改后相应调整的小部件上设置自定义字体大小?

问题描述

我正在使用 Qt4(我知道),并且有一个自定义小部件可以设置粗体,其磅值是应用程序字体磅值的 1.5 倍。这没有问题。

现在的问题是,如果应用程序字体大小发生变化,小部件的字体大小不会相应地更新(如预期的那样)。我最初的想法是按照以下方式做一些事情:

void MyCustomWidget::changeEvent(QEvent* e)
{
  if (e->type() == QEvent::FontChange)
  {
     setFont(boldAndBigFont());
  }
  return QWidget::changeEvent(e);
}

这不起作用,因为 setFont() 调用将触发 FontChange 事件,从而导致对更改事件处理程序的无休止调用。我注意到还有 ApplicationFontChange,这是有希望的,但是该事件没有传递到我的自定义小部件(我使用事件侦听器进行了验证)。查看 Qt 代码,负责传播 ApplicationFontChange 事件的代码只会将此事件传递给少数选定的小部件(例如主窗口)。

所以我的问题是;如何以一种好的方式解决这个问题?我的一个限制是我不能使用样式表。

我当前的解决方案倾向于自定义字体更改事件,在收到 ApplicationFontChange 后从主窗口触发,但我肯定不会是第一个遇到此问题的人......?

更新:我发现调用 QApplication::setFont(bigAndBoldFont(),"MyCustomWidget"); 也有效。我不是特别喜欢它,因为我宁愿将这种样式行为与自定义小部件的实现联系起来。

解决方法

我不能保证 Qt4,但以下 changeEvent 实现似乎在 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);
  }