How to size QPushButtons to width of text and pack left?
Unsolved
General and Desktop
-
I have two buttons on a QVBoxLayout and am trying to make the buttons the width of their text and not strech across the complete QVBoxLayout. Should have both buttons packed to the left.
I've tried the following to no avail.
auto *button1 = new QPushButton(QLatin1String("b1"), parent); auto *button2 = new QPushButton(QLatin1String("b2"), parent); auto s1 = button1->fontMetrics().size(Qt::TextShowMnemonic, button1->text()); auto s2 = button2->fontMetrics().size(Qt::TextShowMnemonic, button2->text()); QStyleOptionButton opt1; opt1.initFrom(button1); opt1.rect.setSize(s1); QStyleOptionButton opt2; opt2.initFrom(button2); opt2.rect.setSize(s2); button1->setMinimumSize(button1->style()->sizeFromContents( QStyle::CT_PushButton, &opt1, textSize, button1)); button2->setMinimumSize(button2->style()->sizeFromContents( QStyle::CT_PushButton, &opt2, textSize, button2)); QHBoxLayout *controlsLayout = new QHBoxLayout; controlsLayout->addWidget(button1); controlsLayout->addWidget(button2); QVBoxLayout *renderLayout = new QVBoxLayout; renderLayout->addLayout(renderControlsLayout); renderLayout->setContentsMargins(0, 0, 0, 0);
Anyone have thoughts?
-
???What are you doing?
Setting size in a layout is meaningless, they will be resized by the layout in anytime.
You should use layout functions to control their size, instead of calculating by yourself.auto *button1 = new QPushButton(QLatin1String("b1"), parent); button1->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); auto *button2 = new QPushButton(QLatin1String("b2"), parent); button2->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QVBoxLayout *renderLayout = new QVBoxLayout; renderLayout->addWidget(button1, 0, Qt::AlignLeft); renderLayout->addWidget(button2, 0, Qt::AlignLeft);
Here's the problem, by default
QPushButton
has a minimum size hint of about (80, 20) in all kinds of styles.
So if your text is not long enough, it will probably use 80 as the width.
If you need it to be shorter, I prefer usingQToolButton
instead, it doesn't have such minimum value.