Increase button font size when button size is changing

旧时模样 提交于 2019-12-10 18:49:15

问题


I'm having a Qt application with a main window that has five buttons aligned in a vertical order. They all have the same size.

All I want to do is to increase the font size of the button label when the app goes fullscreen. I would really appreciate a solution that does not need too much code ... was hoping that this was something that could be done in Qt Designer, but I couldn't find a way how to.

Any suggestions?

Best,

guitarflow


回答1:


I can't think of any way to do it in designer, but it's really not too much code. Here's a quick-and-dirty proof of concept. You'd want to take into account margins (using QStyle::pixelMetrics and the like), but you get the idea.

#include <QtGui>

class FontAdjustingButton : public QPushButton {
public:
  explicit FontAdjustingButton(QWidget *parent = NULL) : QPushButton(parent) {
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  }
protected:
  void resizeEvent(QResizeEvent *event) {
    int button_margin = style()->pixelMetric(QStyle::PM_ButtonMargin);
    QFont f = font();
    f.setPixelSize(event->size().height() - button_margin * 2);
    setFont(f);
  }
};

int main(int argc, char **argv) {
  QApplication app(argc, argv);
  QWidget w;
  QVBoxLayout *layout = new QVBoxLayout;
  for (int i = 0; i < 5; ++i) {
    FontAdjustingButton *btn = new FontAdjustingButton;
    btn->setText(QString("Hello, world %1").arg(i));
    layout->addWidget(btn);
  }
  w.setLayout(layout);
  w.show();
  return app.exec();
}


来源:https://stackoverflow.com/questions/8052201/increase-button-font-size-when-button-size-is-changing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!