Krzysztof Stanisławek
Krzysztof Stanisławek

Reputation: 1277

QWidget resizing problems

I'm fighting for hours with following problem.

Widget A is container with QHBoxLayout for QLabel objects. I want to put such widget in other widget, with constant height equal to A's height, and minimum width equal to A's width (but width can be changed).

In A constructor I have following code:

QHBoxLayout* mLayout = new QHBoxLayout();
for (auto e : wordsList)
    mLayout->addWidget(e);
mLayout->setSpacing(0);
mLayout->setMargin(0);
mLayout->setSizeConstraint(QLayout::SetFixedSize);
setLayout(mLayout);

And there is the body of B:

class B : public QWidget
{
    Q_OBJECT
public:
    explicit B(A *a0, QWidget *parent = 0)
        : QWidget(parent),
          a(a0)
    {
        a->setParent(this);
        setSizePolicy(QSizePolicy());
        setFixedSize(sizeHint());
    }
    QSize minimumSize() const
    {
        return a->size();
    }
    QSize sizeHint() const
    {
        return minimumSize();
    }
private:
    A *a;
};

In main() I call show() on B's instance. In effect, I get big, fully resizeable window, bigger than A. A is frozen, doesn't resize with B.

I want B to start with the same size as A and to be resizeable only horizontally (but with minimum width equal to A).

How can I achieve this?

And why setSizePolicy() and setFixedSize(), minimumSize() and even sizeHint() don't work?

Can this be because I use B as a main window?

If I use layout in B, this probably should be another QHBoxLayout. But when he has too much space, he fits his component, so I would need to use QSpacerItem and resize him always, when B is resizing. But I don't know order, in which widgets are receiving QResizeEvent: if B gets it before my spacer, I will do nothing. I probably could use eventFilter, but still, this is too complicated (behaviour I need is pretty simple!).

Upvotes: 1

Views: 1684

Answers (1)

Uga Buga
Uga Buga

Reputation: 1784

I think there is no need to inherit B you can just add a layout in B and add A to the layout:

QWidget * widgetB = new WhateverWidgetYouWant();
QHBoxLayout* layoutForB = new QHBoxLayout();
widgetB->setLayout(mLayout);
layoutForB->addWidget(pointerToA);

What you need is to change the size policy of A to Expanding or Preffered or experiment with some other policies. You can test this in the designer and when you are satisfied with the results you can get the right properties and set them in your code.

Upvotes: 1

Related Questions