Important: Please read the Qt Code of Conduct -

QPushButton won't top align in QGridLayout

  • I have a QVBoxLayout that contains a top-aligned QLineEdit and a top-aligned QWidget with the layout set as a QGridLayout. I then programmatically add top-aligned QPushButtons to the QGridLayout depending on user input. This all works, but the problem I'm having is that the QPushButton does not top-align in the QGridLayout. Here's some code snippets I'm hoping will help.

    Main Layout

    this->m_filterBox = new QLineEdit(tr(""));
    connect(m_filterBox, &QLineEdit::textChanged, this, &CMainWindow::filterChanged);
    QVBoxLayout *layout = new QVBoxLayout();
    layout->setAlignment(this->m_filterBox, Qt::AlignTop);
    this->m_keyGrid = new QGridLayout();
    QWidget *gridWidget = new QWidget();
    layout->setAlignment(gridWidget, Qt::AlignTop);
    QWidget *window = new QWidget(this);

    Adding buttons

    int row = 0;
    int column = 0;
    for(std::vector<QString>::iterator it = this->m_vecStrings.begin(); it != this->m_vecStrings.end(); ++it) {
        QString input = *it;
        QPushButton *button = new QPushButton(input);
        this->m_keyGrid->addWidget(button, row, column, 1, 1, Qt::AlignTop);
        if (column > 2) {
            column = 0;

    Any insight is appreciated. Here's a screenshot of what I'm getting for more information

  • So you want the pushbuttons right beneath the lineEdit? See this

    "If the stretch factor is 0 and nothing else in the QBoxLayout has a stretch factor greater than zero, the space is distributed according to the QWidget:sizePolicy() of each widget that's involved.

    The alignment is specified by alignment. The default alignment is 0, which means that the widget fills the entire cell."

    Let me know if that helps

    EDIT: Also, have a look at

    Maybe you can try setting the spacing of the rows to be small so that the buttons appear near top

  • Thanks @MaxDevI, that worked perfectly!

Log in to reply