Nominate our 2022 Qt Champions!

QPushButton->layout() returns 0

  • Hello there,

    so I have a QPushButton in a QHBoxLayout that also contains a QLineEdit. The QHBoxLayout is in a QVBoxLayout. I would like to remove the QHBoxLayout and everything in it(QPushButton and QLineEdit) when I click the QPushButton.

    So I have the button connected to a slot that should do the work that looks like this

    void ClassName::removeLine()
        QPushButton *button = qobject_cast<QPushButton *>(sender()); // get the caller object(QPushButton)
        if (button)
            disconnect(button, SIGNAL(clicked(bool)), this, SLOT(removeLine()));
            QLayout *layout = button->layout();
            if (layout)
                QLayoutItem * item;
                while ((item = layout->takeAt(0)) != 0)
                    delete item->widget();
                    delete item;
                delete layout;

    but button->layout() returns 0. I believe I'm misunderstanding the ::layout() function.

  • Moderators

    I believe I'm misunderstanding the ::layout() function

    Yup, unfortunately. layout() returns the layout of the widget, not the layout it is placed in. So since there are no layouts "inside" a button its layout() method returns null. There's no direct way to tell what layout is managing a given widget i.e. there's no way to go "up" in the hierarchy of layouts. For that you need to get a parent widget (via parentWidget() method) and look for the layout you are interested in the parent layout's items.

    For this sort of task it's easier to put the button and line edit in a dummy "row" QWidget parent, instead of nesting layouts directly. This way you could just do button->parentWidget()->deleteLater() and be done with it.

  • @Chris-Kawa
    Thank you mate, that did the job.

    QWidget *row = new QWidget();
    QLineEdit *line = new QLineEdit(row);
    QPushButton *removeButton = new QPushButton("x", row);
    QHBoxLayout *rowLayout = new QHBoxLayout(row);

Log in to reply