Question

I want make window at Qt UI Designer with part of window replaceable by some condition. So I want design all parts of window by Qt UI Design and switch between them dynamically on designed application at run-time. For example, part of window can be rectangle panel with widgets. What is most properly ways?

Was it helpful?

Solution

You can use layouts:

red border line is QHBoxLayout

Red border line is QHBoxLayout.

Drag and drop layout that you need from left panel with ui elements to form in Qt Designer (i renamed layout as mainLt). Then you will be able to write following code:

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

void Widget::keyPressEvent(QKeyEvent *)
{
    ui->mainLt->removeWidget(ui->label);
    ui->label->hide();
    ui->mainLt->insertWidget(0, new QSpinBox());
}

This code replaces QLabel at left with QSpinBox. So when you show window it looks like:

Window state before press any key

then you press any key...

Window state after press any key

voila!

This small example is pretty buggy: two spin boxes appears because i use Alt+PrintScreen for take a screenshot, which means i pressed two buttons and pressEvent has invoked twice :) But i think you get it. Draw widgets and add them to layouts according your design. After your conditions became true, remove ones widgets and insert anothers.

OTHER TIPS

One approach you can use is to place a QScrollArea widgets in your UI and use the QScrollArea::setWidget function to set the internal widget.

There are two benefits to this approach. First, QScrollArea provides a simple API for getting and setting the internal widgets. And second, QScrollArea will be able to handle any size widget and will show a scrollbar if the inner widget exceeds the size constraints of the scroll area.

For more information, you can take a look at Qt's documentation for the QScrollArea class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top