[Solved] Force QScrollArea to add items from top down with equal spacing?



  • I've got some test code (below) to add items to a QScrollArea. I've worked out most of the issues but I don't know how to force the items to be placed progressively from the top down (stacked under each other). The QScrollArea is laid out in a .ui file and the rest is done through code. Have tried spacing, alignment etc. without success. Any tips?

    Buttons seem to be added at equal divisions of the available space until there are enough items to force a scroll. The second image is how I want them spaced no matter how many items there are.

    Bad
    !http://roypardi.com/temp_images/button.png(Example)!

    Good
    !http://roypardi.com/temp_images/button2.png(Example2)!

    Called at start up
    @ ui->myScroll->setWidgetResizable(true);
    v = new QVBoxLayout;
    v->setContentsMargins(5,5,5,0);
    v->setSpacing(0);
    ui->myScroll->widget()->setLayout(v);
    ui->myScroll->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
    ui->myScroll->setAlignment(Qt::AlignTop);

    // ui->myScroll->setContentsMargins(5,5,5,200);
    // v->setAlignment( ui->myScroll, Qt::AlignTop);//does nothing@
    

    Method to add items
    @void MainWindow::on_pushButton_clicked()
    {
    QPushButton *b = new QPushButton(this);
    b->setText(QString("Hello Button"));
    b->setMinimumHeight(40);
    b->setMinimumWidth(100);

       QHBoxLayout *h = new QHBoxLayout();
       h->addWidget(b,0, Qt::AlignLeft);
       h->setAlignment(Qt::AlignTop);
       // h->setSpacing(0);
       // h->addStrut(12);
       // h->setContentsMargins(5,5,5,0);
       // h->addSpacing(112);
       v->addLayout(h);
       // QSpacerItem *item = new QSpacerItem(1,500, QSizePolicy::Expanding, QSizePolicy::Expanding);
       // v->addSpacerItem(item);
    

    }@



  • The spacing of the buttons is a function of the layout of the container widget (i.e. whatever "v" is set on), not the scroll area. I suggest you try v->setSizeConstraint(QLayout::SetFixedSize) and the layout should force the container widget to track the total vertical size hints of the contained widgets.



  • That works – thanks!


Log in to reply
 

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