[solved] Aligning widgets in center horizontally in a vertical box layout



  • I have a widget with a vertical box layout in it and I want to line up the widgets in the center as they are different widths. I tried "layout->setAlignment(Qt::AlignHCenter);" but that does not seem to do anything. Everything still aligns on the left.

    Here is some test code I was playing around with.

    @int main(int argc, char *argv[]) {

    QApplication app(argc, argv);
    
    QWidget *win = new QWidget();
    
    QVBoxLayout* layout = new QVBoxLayout(win);
    layout->setAlignment(Qt::AlignHCenter);
    
    QFrame * line = new QFrame(win);
    line->setObjectName(QString::fromUtf8("line"));
    line->setFrameShape(QFrame::HLine);
    line->setLineWidth(2);
    line->setFrameShadow(QFrame::Plain);
    layout->insertWidget(0, line);
    
    QLineEdit* ln1 = new QLineEdit();
    ln1->setText("1");
    ln1->setFixedWidth(ln1->width() / 4);
    

    // ln1->setAlignment(Qt::AlignHCenter); // this aligns the text in lineEdit
    layout->insertWidget(0, ln1);

    QLineEdit* ln2 = new QLineEdit();
    ln2->setText("2");
    layout->insertWidget(6, ln2);
    
    win->show();
    
    return app.exec();
    

    }
    @



  • try this
    QLayout::setAlignment ( QWidget * w, Qt::Alignment alignment )
    meaning layout->setAlignment(line, Qt::AlignHCenter);

    (repeat for each one)

    and btw, where do you apply the layout for the widget?
    win->setLayout(layout); or is it automatically applied with the layout constructor?



  • [quote author="inspired" date="1357148829"]try this
    QLayout::setAlignment ( QWidget * w, Qt::Alignment alignment )
    meaning layout->setAlignment(line, Qt::AlignHCenter);

    (repeat for each one)

    and btw, where do you apply the layout for the widget?
    win->setLayout(layout); or is it automatically applied with the layout constructor?[/quote]

    Thanks Inspired. That seems to work. If I apply the alignment to the frame/line it will diaper, but I do not need to center it so we should be fine.

    I guess the layout gets applied to the widget when I set its parent in the constructor. I seems to work that way although I never did see that in the documentation.


Log in to reply
 

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