问题
I have a QPushButton
QPushButton *btn = new QPushButton();
btn->setText("Push \n Button");
The result is:
I have tried btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred)
with Qt Designer but it does not help.
How can do so that the height of the button is automatically adjusted to fit with the content when I call setText
?
回答1:
You can set the vertical size policy to an option that allows the widget to grow, the default option for vertical size policy of QPushButton
is fixed, you can do it like this from code:
btn->setText("Push \n Button");
btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
You can change it in designer, if you use that to create your ui. See more options in the documentation here and choose the one that best suits your needs.
Also use layouts for your widgets, those help a lot, especially if your windows can change size.
来源:https://stackoverflow.com/questions/58728873/how-to-make-height-of-a-qpushbutton-automatically-fit-the-text