QLineEdit validator memory management
I'd like to set QIntValidator for QLineEdit multiple times without having to store pointer of said validator. And that looks something like this:
lineEdit->setValidator(new QIntValidator(1, 2)); //some code lineEdit->setValidator(new QIntValidator(2, 3));
So at this point I'm not sure if setting new validator deletes the old one.
If not can i delete it by doing the following:
Or do I have to cast it?
delete qobject_cast<const QIntValidator *>(lineEdit->validator());
No need to cast, thanks to polymorphism.
Edit: the docs appear not so clear to me, but if setting a
nullptrvalidator unsets the current one, I'd bet setting a new one would properly delete the old one.
AFAIK, no it doesn't delete anything. The QLineEdit object doesn't become the owner of the validator. Also, if you take look at the examples, all create a QValidator object with the parent being the widget the validator is set on.
@SGaist In this example http://doc.qt.io/qt-5.8/qtwidgets-widgets-lineedits-example.html QIntValidator parent is set to QLineEdit and it appears that there is a memory leak.
So the solution would be( thanks to @JohanSolo ) :
No there's not, the QIntValidator gets the QLineEdit as parent and thus it will get deleted at the same time as the widget.
No leak per se but indeed, if you start to change the validator frequently you'll have a bunch of unused objects lying around that will get deleted when the widget is destroyed.
I'd recommend calling
deleteLaterso you ensure that if there are events pending nothing goes wrong.