0

我有一个名为的类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
};
4

1 回答 1

2

指针的父级File通过MainWindow销毁父级,这些对象将自动销毁,然后您不需要delete它们,这是错误的:

delete fileList.at(0);

另一方面,从中移除一个项目fileList并没有什么坏处,而且没关系:

fileList.removeAt(0);

这是代码没有意义:

File::~File()
{
  delete m_textEdit; //QTextEdit* - Crashes here
  delete m_tab; //QWidget* //Doesn't reach this line
}

因为,你从构造函数中获取m_textEditm_tab,而你没有new通过File. 所以,delete这里对他们来说是不正确的。不要碰它们。

于 2013-10-01T14:55:59.390 回答