Search code examples
pythonpyqtargumentsqvalidator

Proper usage of QValidator


I use validators to filter user input. Normally I have my validators working like this:

my_reg_ex = QRegExp("[1-9]\d{0,5}")
my_validator = QRegExpValidator(my_reg_ex, self.ui.lineEdit_test)
self.ui.lineEdit_test.setValidator(my_validator)

I wrote this after looking at some examples online. But I just noticed that if I remove the last part on the second line:

, self.ui.lineEdit_test

The code works exactly the same. I have a couple of these validators all around. I was wondering if it's okay to just use it without the part I mentioned. For example:

my_reg_ex = QRegExp("[1-9]\d{0,5}")
my_validator = QRegExpValidator(my_reg_ex)
self.ui.lineEdit_test.setValidator(my_validator)

Is there any difference between these? If there is please explain and tell me which one is the better way to go.


Solution

  • The QRegExpValidator class inherits QObject, so its constructor has an argument that takes a parent QObject. One general reason for setting a parent, is to ensure the object doesn't get garbage-collected when it goes out of scope. This can easily happen if you don't keep any other reference to the object, and is a very common cause of many of the problems seen in newbie questions on SO.

    However, this is actually not a problem in your specific example. This is because the line-edit takes ownership of the validator when you pass it to setValidator(), so you don't need to explicitly keep a reference to it yourself. As far as the code in your question is concerned, it really makes no difference whether you set a parent or not.

    Having said that, there is at least one scenario where not setting a parent may be advantageous. This could arise if you needed to regularly reset the validator at runtime. If you gave each new validator a parent, the old one would not be deleted when setValidator() is called (because the parent would still hold a reference to it). So for the purposes of simplifying object-cleanup, not setting a parent in this situation might be preferrable.