Important: Please read the Qt Code of Conduct -

Having problems deleting and adding widgets to a layout.

  • So basically I've got a situation where I've got a square grid of QLineEdit widgets. So I've got a function that builds the grid that gets called by the constructor for the grid object and is signaled by pressing return on a QLineEdit to change the dimension, it looks something like this:

    void GridUI::buildGrid() {
        //Grab the dimension size from the input
        gridDimension = dimensionInput->text().toInt();
        //Delete all the widgets in the grid if they already exist
        //puzzleGridCell is a QGridLayout instantiated in the constructor
        QLayoutItem *toDelete;
        while ((toDelete = puzzleGridCell->takeAt(0)) != 0)
            delete toDelete->widget();
        //Create the grid
        for (int puzzCol = 0; puzzCol < gridDimension; ++puzzCol) {
            for (int puzzRow = 0; puzzRow < gridDimension; ++puzzRow) {
                QLineEdit *puzzBox = new QLineEdit("", this);
                puzzleGridCell->addWidget(puzzBox, puzzCol, puzzRow);

    What's going wrong is that it's building properly to start, but when I change the dimension and press return it removes all of the QLineEdits, but doesn't seem to resize the grid or show the new QLineEdit widgets, I can tell through debugging that they're at least getting created and added to the QGridLayout, but they're just not showing up at all.

    Just wanted to see if there was something really obvious that I'm not aware of, or maybe if anyone's got any ideas on what to look at.

  • Lifetime Qt Champion

    @blakejustblake The new line edits are not shown because you do not call show() on them:

    QLineEdit *puzzBox = new QLineEdit("", this);
    puzzleGridCell->addWidget(puzzBox, puzzCol, puzzRow);

  • @jsulm Definitely something obvious I wasn't aware of. Thanks. So if add any children after initially showing a widget I need to additionally show them as well?

  • Lifetime Qt Champion

    @blakejustblake Yes, you need to call show()

Log in to reply