Important: Please read the Qt Code of Conduct -

How to size QPushButtons to width of text and pack left?

  • 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;
    QStyleOptionButton opt2;
        QStyle::CT_PushButton, &opt1, textSize, button1));
        QStyle::CT_PushButton, &opt2, textSize, button2));
    QHBoxLayout *controlsLayout = new QHBoxLayout;
    QVBoxLayout *renderLayout = new QVBoxLayout;
    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 using QToolButton instead, it doesn't have such minimum value.

  • Lifetime Qt Champion


    To ensure they are pushed to the left, add a stretch after the last button.

Log in to reply