I have a Class called File
which contains a QTextEdit*
(a textbox), a QWidget*
(used to create tabs in a QTabWidget
), a QString
for holding an address of a file and a bool
to check whether the file has been saved / modified.
I store these files in a QList
(it's just like the std::list
).
void MainWindow::newFile()
{
QWidget* tab = new QWidget( tabWidget ); //QTabWidget is a member of MainWindow, it gets automatically deleted when MainWindow gets destryoed
tabWidget->addTab( tab, tr("New Tab") ); //Add it to the QTabWidget
tab->setLayout( new QHBoxLayout( tab ) );
QTextEdit* textEdit = new QTextEdit( tab ); //When tab gets deleted, this also gets deleted
tab->layout()->addWidget( textEdit );
File *f = new File( this, textEdit, tab ); //Store both in a file
fileList.push_back( f ); //Add it to the list (member of MainWindow)
tabWidget->setCurrentIndex( tabWidget->count()-1 ); //Go to that tabPage
f->textEdit()->setFocus(); //Set the focus to the textEdit
}
This creates a new tabpage, adds it to the QTabWidget
, creates a layout for the tabpage, creates a new QTextEdit
, adds it to the layout so it's filled and will automatically resize and finally it gets pushed back onto the QList
so I can remove the tab etc.
Since the class File
has pointers as member their objects on the heap have to be deleted. But when I try to delete them in the destructor I get a SIGSEGV and my program crashes.
File::~File()
{
delete m_textEdit; //QTextEdit* - Crashes here
delete m_tab; //QWidget* //Doesn't reach this line
}
My question now is, why does my program crash when I try to delete m_textEdit
's object? This only happens when I close the window.
Also, do I have to delete the File* when I remove them from the list? Or does the list do it automatically for me? If so, how do I do it?
//delete fileList.at(0); //This would cause a crash
fileList.removeAt( 0 ); //removing for example the first index
Edit: Headerfile of File
class File : public QObject
{
Q_OBJECT
QTextEdit* m_textEdit;
QWidget* m_tab;
QString m_filepath;
bool m_saved;
public:
explicit File(QObject *parent = 0);
File( const File& );
File( QObject* parent, QTextEdit* textEdit = 0, QWidget* tab = 0, const QString& filepath = QString(), bool saved = true );
~File();
signals:
void savedChanges( bool );
public slots:
//Getters and setters only
};
The parent of the pointers to File
is MainWindow
so by destroying the parent those objects will be destroyed automatically, then you don't need to delete
them and this is wrong:
delete fileList.at(0);
On the other hand, removing an item from fileList
doesn't hurt and it's OK:
fileList.removeAt(0);
This is code doesn't make sense:
File::~File()
{
delete m_textEdit; //QTextEdit* - Crashes here
delete m_tab; //QWidget* //Doesn't reach this line
}
Because, you're getting m_textEdit
and m_tab
from the constructor, and you didn't new
them by File
. So, it's not correct to delete
them here. Don't touch them.