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;
}
}
@ -
-
call delete directly is not a good, give a try to QObject::deleteLater()
-
Change you code to
@
ui->widget->findChildren<QWidget *>(QString(), Qt::FindDirectChildOnly)
@if they have sub children.
-