Qt World Summit: Register Today!

SOLVED: Application crashes when removing tableWidget

  • Hello,

    I have been struggling with issues related to tableWidgets. Now my app crashes whenever I try to delete a table from it's parent widget. Below is the code for MainWindow.cpp, addButton and removeButton connect to the two functions. So could you please show me why the application crashes when removeButton is clicked?

    @#include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QTableWidget>

    MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)

    connect(ui->addButton, SIGNAL(clicked()), this, SLOT(add_table()));
    connect(ui->removeButton, SIGNAL(clicked()), this, SLOT(remove_table()));


    delete ui;

    void MainWindow::add_table()
    //Create table
    QTableWidget *tableWidget = new QTableWidget(ui->widget);

    QTableWidgetItem *item = new QTableWidgetItem("hello");
    tableWidget->setItem(0, 0, item);


    void MainWindow::remove_table()
    //Remove table by removing all children
    QList<QWidget *> Widgets = ui->widget->findChildren<QWidget *>();
    foreach(QWidget * child, Widgets)
    delete child;

    1. call delete directly is not a good, give a try to QObject::deleteLater()

    2. Change you code to

    ui->widget->findChildren<QWidget *>(QString(), Qt::FindDirectChildOnly)

    if they have sub children.

Log in to reply