Increase button font size when button size is chan

2019-07-04 01:35发布

问题:

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