c++11qt5qgridlayoutqvboxlayout

How to properly use QGridLayout to addWidgets next to each other in Qt5


I have a small problem trying to put two layouts next to each other.

The actual result I have so far is the followig:

layoutwrong

But it should look like this one below:

layoutok

What am I missing?

Below the small snippet of code I am using for this:

MyViz::MyViz(QWidget *parent) : QWidget(parent)
{

//  Qt Components set up......

QGridLayout* control_layout = new QGridLayout();
control_layout->addWidget(thickness_label, 0, 0);
control_layout->addWidget(thickness_slider, 0, 1);
control_layout->addWidget(cell_size_label, 1, 0);
control_layout->addWidget(cell_size_slider, 1, 1);

control_layout->addWidget(thickness_label_second_renderer, 0, 2);
control_layout->addWidget(thickness_slider_second_renderer, 0, 3);
control_layout->addWidget(cell_size_second_renderer_label, 1, 2);
control_layout->addWidget(cell_size_second_renderer_slider, 1, 3);


// construct lay-out and render panels next to each other
render_panel = new rviz::RenderPanel();
render_panel2 = new rviz::RenderPanel();

QVBoxLayout* main_layout = new QVBoxLayout;
main_layout->addLayout(control_layout);
main_layout->addWidget(render_panel);
main_layout->addWidget(render_panel2);

// set the top-leve layout for this MyViz widget
setLayout(main_layout);

// other operation....

}

Solution

  • The problem is that you are creating a QVBoxLayout ('V' for vertical) and placing your QGridLayout and RenderPanel instances in it. Just put everything in the QGridLayout...

    MyViz::MyViz(QWidget *parent) : QWidget(parent)
    {
    
        //  Qt Components set up......
    
        QGridLayout* control_layout = new QGridLayout();
        control_layout->addWidget(thickness_label, 0, 0);
        control_layout->addWidget(thickness_slider, 0, 1);
        control_layout->addWidget(cell_size_label, 1, 0);
        control_layout->addWidget(cell_size_slider, 1, 1);
    
        control_layout->addWidget(thickness_label_second_renderer, 0, 2);
        control_layout->addWidget(thickness_slider_second_renderer, 0, 3);
        control_layout->addWidget(cell_size_second_renderer_label, 1, 2);
        control_layout->addWidget(cell_size_second_renderer_slider, 1, 3);
    
    
        // construct lay-out and render panels next to each other
        render_panel = new rviz::RenderPanel();
        render_panel2 = new rviz::RenderPanel();
    
        /*
         * At this point the QGridLayout has 4 occupied columns.  Make
         * each rviz::RenderPanel instance span 2 columns.
         */
        control_layout->addWidget(render_panel,  2, 0, 1, 2);
        control_layout->addWidget(render_panel2, 2, 2, 1, 2);
    
        // set the top-level layout for this MyViz widget
        setLayout(control_layout);
    
        // other operation....
    
    }
    

    Noting that the 4th and 5th parameters passed to QGridLayout::addWidget are the row and column span respectively.