需要手动删除 QValidator 吗?

Need to delete QValidator manually?

示例代码:

QDoubleValidator *validator = new QDoubleValidator();
myInputLineEdit->setValidator(validator);

// delete validator;

注意:myInputLineEdit 是一个 QLineEdit 指针,将与其父项一起删除。

我的问题是,我应该什么时候删除验证器,因为它是手动创建的,而且根据文档,setValidator() 似乎没有取得此指针的所有权?如果我不删除,会不会内存泄露?

我试图在之后立即删除它,就像注释代码一样,我注意到在那之后 myInputLineEdit 的验证器变成了 0。所以我想我可能需要在myInputLineEdit被删除后删除它。

另一个想法是,我可以给验证器一个父节点,这样它就会连同它的父节点一起被删除,这是一个很好的方法吗?如果没有合适的家长候选人怎么办?

谢谢

使用 mInputLineEdit 作为 validatorparent,如示例 here. The destructor of a parent destroys all child objects (see this). This is the "qt way" of handling ownership trees

I tried to delete it right after, like the commented code, and I noticed the validator of myInputLineEdit became 0 after that. So I think I may need to delete it after myInputLineEdit is deleted.

这是因为 QLineEdit 在内部使用 QPointer,如果对象被删除,它会跟踪 QValidator

and setValidator() doesn't seem to take ownership of this pointer according to the documentation

setValidator() 确实没有设置 QValidator 的父级。

Another thought is, I could give validator a parent so it will be deleted along with its parrent, is this a good way to do that? What if there isn't a good candidator to be the parent?

您可以手动删除它,使用智能指针或像@crayzeewulf 所说的那样 - 将 myInputLineEdit 设置为父级(使用 QValidator 构造函数或 setParent())。父级负责删除其子级,因此这是一种可行的方法。通常分配验证器的对象是一个好的父对象。

If I don't delete it, will it be a memory leak?

如果既不设置也不删除parent,会出现内存泄漏。