For QObject
members as pointers, you shouldn t use delete
, the QTextEdit
will probably be a child of MainWindow
, so it will be deleted automatically.
It would, of course, be theoretically faster to use non-pointer QObject
members, with one less level of indirection. Like this (for those who didn t understand the question):
class MainWindow : public QMainWindow {
...
private:
QTextEdit textEdit;
};
而分类法也较少,因为你不必重写成员类别名称,以在建筑商中开始。
But since QObject
are themselves already heavily using indirection (with their d-pointer), the gain will probably be negligible. And the extra code you type with pointer members allows you to have a lower coupling between your header files and Qt, because you can use forward declarations instead of header inclusion, which means faster compilations (especially if you are not using precompiled headers yet) and recompilations.
此外,
- manually deleting
QObject
pointer members, or
- declaring
QObject
as non-pointers members
can causes double deletion, if you don t respectively delete/declare them in the right order (children then parents for deletion, or parents then children for declaration).
For example:
class MainWindow : public QMainWindow {
...
private:
QTextEdit textEdit;
QScrollArea scrollArea;
};
MainWindow::MainWindow() {
setCentralWidget(&scrollArea);
QWidget *scrolledWidget = new QWidget(&scrollArea);
QVBoxLayout *lay = new QVBoxLayout(scrolledWidget);
lay->addWidget(...);
lay->addWidget(&textEdit); // textEdit becomes a grand-child of scrollArea
scrollArea.setWidget(scrolledWidget);
}
在删除“MainWindow时,其非法定类别成员按其在该类声明的相反顺序删除。 http://code>scrollArea,首先销毁textEdit
,但scroll 《区域代码>还销毁了儿童,包括<>编码>textEdit
,从而有效销毁了造成坠毁的两倍。
So it is less error prone to use QObject
members as pointers, and to not delete the QObject
which have a parent yourself.