我的编码习惯使用Qt可以被描述为在QMainWindow中构造的“新”使用的UI组件如下:混淆
- 如果控件将被积极使用(如A
QLineEdit
提供文本),我在头文件中声明它,然后在MainWindow.cpp
中初始化它。 例如TextEditor.h:
class TextEditor { //other code private: QLineEdit edtFind; };
2。如果一个部件是不会被使用(例如QLabel
,QWidget
),或它的一个信号时隙系统(例如QPushButton)的一部分,我声明和使用新的inialise它在构造函数中。
-e.g.
TextEditor::TextEditor()
{
//other code
QWidget* searchPanel = new QWidget();
edtFind = new QLineEdit("Enter Search Term");
QPushButton* findButton = new QPushButton("Find");
connect(findButton,SIGNAL(pressed()),this,SLOT(find()));
ui->statusbar->addPermanentWidget(searchPanel);
}
我的问题是,我在第2点使用有效的方法?不从堆中分配内存会更好吗?
谢谢。
使用'new'分配的内存分配在堆上。所以你已经在第二点做到了。顺便说一句,变量应该是类成员,只要它们是该类的_property_,并且变量应该具有最窄的生命周期和范围。 – 2012-01-02 08:44:12