Shf
Shf

Reputation: 3493

Arrange widgets in layout

i want to achieve following layout behavior:

    | A  |  B  |       | A  |     |
 1) |---- -----|    2) |----   D  |
    | C  |  D  |       | C  |     |

Align A,B,C,D with each other and allow D to take available space if B is hidden.

I can achieve layout behaviors 1 or 2 with multiple ways. But i cannot seem to find solution to satisfy both of these conditions without removing widgets from layouts and re-adding later when B hides/shows with qt default layouts.

I tried so far:

1) grid layout - when B is hidden, D stays in place. Can align like i want if i will start to track hide-show status of widget B.

2) combinations of hbox and vbox layouts - D will get all space, after B is hidden, but when B is shown - A and B are never aligned. Once again i'll need to rearrange all widgets to achieve behavior i want.

I suppose Grid layout best suited for my purposes, but row span is set in stone when I add widgets.

Is there simple solution i miss?

Upvotes: 0

Views: 1392

Answers (1)

MBach
MBach

Reputation: 1645

You could try the following code:

#include <QMainWindow>
#include "ui_mainwindow.h"

class MainWindow : public QMainWindow, public Ui::MainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setupUi(this);

    QWidget *left = new QWidget;
    QWidget *right = new QWidget;
    QHBoxLayout *hbox = new QHBoxLayout;
    QVBoxLayout *vboxLeft = new QVBoxLayout;
    QVBoxLayout *vboxRight = new QVBoxLayout;

    vboxLeft->addWidget(new QLabel("A"));
    vboxLeft->addWidget(new QLabel("C"));
    auto b = new QLabel("B");
    vboxRight->addWidget(b);
    vboxRight->addWidget(new QLabel("D"));

    left->setLayout(vboxLeft);
    right->setLayout(vboxRight);

    hbox->addWidget(left);
    hbox->addWidget(right);
    centralWidget()->setLayout(hbox);

    QAction *toggleB = new QAction("Toggle B");
    toggleB->setCheckable(true);
    connect(toggleB, &QAction::toggled, this, [=](bool toggled) {
        b->setHidden(toggled);
    });
    mainToolBar->addAction(toggleB);
}

You can toggle as many times as you want, it will keep the layout clean: toggle layout

Upvotes: 1

Related Questions