PDA

View Full Version : auto resize font in QSpinBox



GoranShekerov
4th March 2015, 13:15
Any idea haw to auto re size the font (point size) of the text in the spin box?


I have a spin box in a window and when resizing the window the spin box is automatically re sized but the point size of the text (font size) in the spin box stays the same.
I've tried to reimplement the MainWindow::resizeEvent() in order to increase the font size according to the new size(height) of the spin box:

void MainWindow::resizeEvent(QResizeEvent */*event*/)
{
ui->spinBox->setStyleSheet(QString("font: %1pt").arg(ui->spinBox- >geometry().height() - 20));
}

but I think that it somehow recursively calls it self, increases the font size to much and crash.

Santosh Reddy
4th March 2015, 13:35
You should call MainWindow::resizeEvent(event) in the end.

Here is another alternate you can try.


class SpinBox : public QSpinBox
{
public:
explicit SpinBox(QWidget * parent = 0) : QSpinBox(parent) { }

protected:
void resizeEvent(QResizeEvent * event)
{
int h = event->size().height();

QFont f = font();
f.setPixelSize(h - 20);
setFont(f);

QSpinBox::resizeEvent(event);
}
};

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

SpinBox s;
s.show();

return a.exec();
}

GoranShekerov
5th March 2015, 11:18
Thank you Santosh for helping,
when I test your code it's ok, but it is the case when you show only the spinbox. Unfortunately if I place the spinbox in a main window, the same recursive calling of the resizeEvent() function happens, the spinbox increases too much and the program crashes. I'v attached the code I'm testing.
Everything best, Goran.

Santosh Reddy
5th March 2015, 12:35
Setting the size policy to Ignore seems to work works

spinbox.setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);