Search code examples
qtqt5qboxlayout

How to have widgets with a fixed width ratio in a Qt box layout


I have four QLabel objects which I need to be part of a QHBoxLayout, making sure the ratios are 50%, 10%, 10%, and 30%, in that order:

▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
         Label 1           L 2   L 3      Label 4

I tried setting the stretch factors to 5, 1, 1, and 3, but then if any of those labels would need to grow because of its text, the layout doesn't honor the ratios.

I need the text of any label to be partial (clipped) if it's too large (if it would normally make the label grow).

Any way to achieve this?


Solution

  • musicamante said:

    Try setting the horizontal size policy of the labels to Ignored.

    Setting the horizontal size policy of labels to QSizePolicy::Ignored works.

    Here's a demo of my own use case:

    int main(int argc, const char *argv[])
    {
        static constexpr auto abc = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
    
        QApplication app {argc, argv};
        QWidget window;
        const auto layout = new QHBoxLayout {&window};
        const auto label1 = new QLabel {abc};
        const auto label2 = new QLabel {abc};
        const auto label3 = new QLabel {abc};
        const auto label4 = new QLabel {abc};
    
        label1->setStyleSheet("color: red;");
        label2->setStyleSheet("color: blue;");
        label3->setStyleSheet("color: green;");
        label4->setStyleSheet("color: orange;");
    
        label1->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
        label2->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
        label3->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
        label4->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
    
        layout->addWidget(label1, 5);
        layout->addWidget(label2, 1);
        layout->addWidget(label3, 1);
        layout->addWidget(label4, 3);
    
        window.show();
        app.exec();
    }
    

    Results:

    1

    2