How to switch between horizontal and vertical layout in Qt
Introduction[edit | edit source]
This example is useful if you want to switch the layout of your widgets i.e. from horizontal to vertical and vice versa.
Here two pushbuttons are displayed in the vertical layout first. When user clicks on the horizontal button, widgets are arranged horizontally.
Code[edit | edit source]
- include <QApplication>
- include <QPushButton>
- include <QVBoxLayout>
- include <QHBoxLayout>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget* win = new QWidget();
QWidget* hwin = new QWidget();
QVBoxLayout* layout = new QVBoxLayout(win);
QHBoxLayout* hlayout = new QHBoxLayout(hwin);
QPushButton* but1 = new QPushButton("Horizontal");
but1->resize(70,20);
layout->addWidget(but1);
QPushButton* but2 = new QPushButton("Vertical");
but2->resize(70,20);
layout->addWidget(but2);
QPushButton* but3 = new QPushButton("Horizontal");
but3->resize(70,20);
hlayout->addWidget(but3);
QPushButton* but4 = new QPushButton("Vertical");
but4->resize(70,20);
hlayout->addWidget(but4);
QObject::connect(but1, SIGNAL(clicked()), hwin, SLOT(show()));
QObject::connect(but1, SIGNAL(clicked()), win, SLOT(hide()));
QObject::connect(but2, SIGNAL(clicked()), win, SLOT(show()));
QObject::connect(but2, SIGNAL(clicked()), hwin, SLOT(hide()));
QObject::connect(but3, SIGNAL(clicked()), hwin, SLOT(show()));
QObject::connect(but3, SIGNAL(clicked()), win, SLOT(hide()));
QObject::connect(but4, SIGNAL(clicked()), win, SLOT(show()));
QObject::connect(but4, SIGNAL(clicked()), hwin, SLOT(hide()));
win->show();
return app.exec();
}