我有一个名为的类File
,它包含一个QTextEdit*
(文本框)、一个QWidget*
(用于在 a 中创建选项卡QTabWidget
)、一个QString
用于保存文件地址和一个bool
用于检查文件是否已保存/修改的类。
我将这些文件存储在一个QList
(就像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
}
这将创建一个新的标签页,将其添加到QTabWidget
,为标签页创建一个布局,创建一个新的QTextEdit
,将其添加到布局中以便填充并自动调整大小,最后它被推回 ,QList
以便我可以删除标签等。
由于该类File
将指针作为成员,因此必须删除堆上的对象。但是当我尝试在析构函数中删除它们时,我得到一个 SIGSEGV 并且我的程序崩溃了。
File::~File()
{
delete m_textEdit; //QTextEdit* - Crashes here
delete m_tab; //QWidget* //Doesn't reach this line
}
我现在的问题是,为什么当我尝试删除m_textEdit
对象时我的程序会崩溃?这只发生在我关闭窗口时。
另外,当我从列表中删除文件*时,我是否必须删除它们?还是列表会自动为我完成?如果是这样,我该怎么做?
//delete fileList.at(0); //This would cause a crash
fileList.removeAt( 0 ); //removing for example the first index
编辑:头文件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
};