Planned maintenance: From Sunday 8th December 10:00 CET there will be changes to try and solve the caching issues that have been experienced. If anyone has a problem connecting after this period then please PM @AndyS or any of the moderators.

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?

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

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);

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

    }

    MainWindow::~MainWindow()
    {
    delete ui;
    }

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

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

    }

    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