Robin Vysloužil
Robin Vysloužil

Reputation: 35

Deleting button in Qt

Writing a school project in c++ and qt. It is supposed to be a block editor (like draw.io). I generate blocks as a buttons and setting them to a grid (code below). But when I try to delete some of the buttons, the whole window closes. What should I do to delete just only one button?

void MainWindow::newBlock() {
    QPushButton *button = new QPushButton(
                tr("SUMblock%1").arg(mainGrid->count())
                );
    QMenu *buttonMenu = new QMenu(this);
    buttonMenu->addAction(editBlockAction);
    buttonMenu->addAction(deleteBlockAct);

    button->setMenu(buttonMenu);

    mainGrid->addWidget(button, posX, posY);
}

void MainWindow::createActions() {

    deleteBlockAct = new QAction(tr("Delete block"), this);
    connect(deleteBlockAct, &QAction::triggered, this, &MainWindow::deleteBlock);
}

void MainWindow::deleteBlock() {
    this->close(); //have no idea what to put here
}

Upvotes: 0

Views: 2768

Answers (1)

CharonX
CharonX

Reputation: 2216

Have you looked into using the remove widget function from qlayout?

Alternatively you could simply hide the button if you do not need to remove it entirely.

Naturally you need to have a pointer to the button to do either, but as I do not know how exactly you determine which Button to delete this may range from simply retaining a list of the buttons, searching for the right button via findChildren, using lambda functions, etc.

Upvotes: 2

Related Questions