只是一个关于亲子关系的快速问题。我一直在阅读教程,但我似乎找不到任何演示“this”关键字正确放置的教程或读物。
这是我的代码:
window::window(){
bar = new QProgressBar;
button = new QPushButton;
bar->setTextVisible(false);
button->setText("IRON LOADER"); //widget
QGridLayout * GL = new QGridLayout(); //layout
GL->addWidget(bar);
GL->addWidget(button);
QGroupBox * gb = new QGroupBox("Group",this); //widget
//second box
QTextEdit * tester = new QTextEdit(); //widget
tester->setFixedHeight(100);
QVBoxLayout * ly = new QVBoxLayout(); //layout
ly->addWidget(tester);
QWidget * widge = new QWidget(this); //widget
//final
widge->setLayout(ly); //first widget group
gb->setLayout(GL); //second widget group
//main wrapper
QGridLayout * test = new QGridLayout;
test->addWidget(widge,0,1);
test->addWidget(gb,0,0);
//set up
QWidget * central = new QWidget;
central->setLayout(test);
setCentralWidget(central); //set central
}
我的程序很简单:
它由3个文件组成,分别是:window.h
、main.cpp
和window.cpp
我从 windows.cpp
继承了 QMainWindow
然后我实现了 2 组小部件:
左边的由一个 QPushButton
和一个 QProgressBar
组成。
右边有一个 QTextEdit
。
我的代码按预期编译和工作。
让我困惑的一件事是:我应该什么时候放this
?不在其中一些上放置 this
关键字可以吗(因为删除父项与关闭程序的时间相同)?
我读到qt上的父/子关系是关于删除和内存管理的。
最佳答案
如果程序泄漏但被终止,操作系统将回收其内存(操作系统跟踪执行的内存分配)。无论如何,为了它而泄漏内存不是一个好的做法,因为您的程序可能会被其他人扩展或使用与以前预期不同的方式。
关于Qt widgets tutorial explains this
As with QObjects, QWidgets can be created with parent objects to indicate ownership, ensuring that objects are deleted when they are no longer used. With widgets, these parent-child relationships have an additional meaning: each child widget is displayed within the screen area occupied by its parent widget. This means that when you delete a window widget, all the child widgets it contains are also deleted.
回答您的问题:在小部件之间设置父子关系对于内存管理和显示正确性都是很好的做法。
关于c++ - 什么时候为 Widget 父构造函数放置 "this"关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31825549/