Make child widget same size as parent layout.



  • Hello

    I have parent QWidget and inside i have QVBoxLayout and inside of that layout single custom widget, custom widget is smaller then parent. how can I fill(make child widget same size inside of parent widget) parent layout with child layout?

    this is not working 100% here. assume that layout is QVBoxLayout in my parent widget.
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);

    please help


  • Moderators

    The above should be enough. Please post your setup code i.e how you set the layout, how you add the widget and (if possible) the relevant part of your custom widget.
    One thing that can affect this is setting margins in a stylesheet of the child or padding in the parent.



  • lets take simple example

    main.cpp

    #include <QApplication>
    #include <QtWidgets>
    #include "simplewidget.h"
    #include <QVBoxLayout>
    #include <QSizePolicy>
    
    int main(int argc, char *argv[]){
        QApplication a(argc, argv);
    
        QWidget *win = new QWidget();
    
    
        win->setStyleSheet("background-color: green");
        win->setFixedHeight(100);
        win->setFixedWidth(200);
        QVBoxLayout *layout = new QVBoxLayout();
        layout->setSpacing(0);
        layout->setContentsMargins(0, 0, 0, 0);
        win->setLayout(layout);
    
        SimpleWidget *simpleWidget = new SimpleWidget();
        layout->addWidget(simpleWidget);
    
        win->show();
        return a.exec();
    }
    

    simple_widget.h

    #ifndef SIMPLEWIDGET_H
    #define SIMPLEWIDGET_H
    
    #include <QWidget>
    
    class SimpleWidget : public QWidget
    {
        Q_OBJECT
    public:
        explicit SimpleWidget(QWidget *parent = 0);
        
    signals:
        
    public slots:
        
    };
    
    #endif // SIMPLEWIDGET_H
    
    

    simplewidget.cpp

    #include "simplewidget.h"
    
    SimpleWidget::SimpleWidget(QWidget *parent) :
        QWidget(parent)
    {
        this->setStyleSheet("background-color: yellow;");
        QSizePolicy po;
        po.setHorizontalPolicy(QSizePolicy::Preferred);
        po.setVerticalPolicy(QSizePolicy::Preferred);
        po.setVerticalStretch(1);
        po.setHorizontalStretch(1);
    
        this->setSizePolicy(po);
    }
    
    

    I have main QWidget with green background and SimpleWidget(extends QWidget) class with yellow background. how stretch SimpleWidget widget ? why i cannot see yellow backgrounded widget?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.