Search code examples
qt5qtableviewqgridlayout

QGridLayout with colspan and rowspan


I can't create a QGridLayout like this one.

enter image description here

I tried but I failed

QGridLayout *layout = new QGridLayout;
layout->addWidget(mytableview,0,0,1,3);
layout->addWidget(b1,1,0,1,1,Qt::AlignRight);
layout->addWidget(b2,1,1,1,1,Qt::AlignRight);
layout->addWidget(b3,1,2,1,1);
mainWindow->setLayout(layout);

Solution

  • You can't do this by using just QGridLayout. For the bottom area you need to use a QHBoxLayout and to use QHBoxLayout::addStretch to add the spacing.

    Here is an example:

    widget.h:

    #ifndef WIDGET_H
    #define WIDGET_H
    
    #include <QWidget>
    
    class QGridLayout;
    class QHBoxLayout;
    class QSpacerItem;
    class QPushButton;
    class QSpacerItem;
    class QPushButton;
    class QPushButton;
    class QTableView;
    
    class Widget : public QWidget
    {
        Q_OBJECT
    
    public:
        explicit Widget(QWidget *parent = 0);
        ~Widget();
    
    private:
        QGridLayout *gridLayout;
        QHBoxLayout *horizontalLayout;
        QSpacerItem *horizontalSpacerLeft;
        QPushButton *pushButtonB1;
        QSpacerItem *horizontalSpacerRight;
        QPushButton *pushButtonB2;
        QPushButton *pushButtonB3;
        QTableView *tableView;
    };
    
    #endif // WIDGET_H
    

    widget.cpp:

    #include "widget.h"
    
    #include<QGridLayout>
    #include<QHBoxLayout>
    #include<QSpacerItem>
    #include<QPushButton>
    #include<QSpacerItem>
    #include<QPushButton>
    #include<QPushButton>
    #include<QTableView>
    
    Widget::Widget(QWidget *parent) :
        QWidget(parent)
    {
        gridLayout = new QGridLayout(this);
        horizontalLayout = new QHBoxLayout();
    
        horizontalLayout->addStretch(3);
    
        pushButtonB1 = new QPushButton(this);
        pushButtonB1->setText("B1");
    
        horizontalLayout->addWidget(pushButtonB1);
    
        horizontalLayout->addStretch(1);
    
        pushButtonB2 = new QPushButton(this);
        pushButtonB2->setText("B2");
    
        horizontalLayout->addWidget(pushButtonB2);
    
        pushButtonB3 = new QPushButton(this);
        pushButtonB3->setText("B3");
    
        horizontalLayout->addWidget(pushButtonB3);
    
        gridLayout->addLayout(horizontalLayout, 1, 0, 1, 1);
    
        tableView = new QTableView(this);
    
        gridLayout->addWidget(tableView, 0, 0, 1, 1);
    }
    
    Widget::~Widget()
    {
    }
    

    main.cpp:

    #include "widget.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        Widget w;
        w.show();
    
        return a.exec();
    }
    

    Result:

    enter image description here