QValidator and dynamic_cast
-
Hi
I have a few LineEdits and according to the type ,if necessery, i need to set a validator and input mask for LineEdits in order to stop user from making a wrong entry.
Here is my code
void MainWindow::prepareInputMaskAndValidator(const QString &type, QValidator * validator, QString &inputMask) { if(type == SQL_TYPE_CHAR) { inputMask = ""; validator = nullptr; } else if(type == SQL_TYPE_INTEGER) { inputMask = ""; validator = new QIntValidator(std::numeric_limits<qint32>::min(), std::numeric_limits<qint32>::max()); } else if(type == SQL_TYPE_FLOAT) { inputMask = ""; validator = new QDoubleValidator(); static_cast<QDoubleValidator*>(validator)->setNotation(QDoubleValidator::StandardNotation); static_cast<QDoubleValidator*>(validator)->setRange(std::numeric_limits<float>::min(), std::numeric_limits<float>::max()); } else if(type == SQL_TYPE_DATE) { inputMask = "0000-00-00"; validator = nullptr; } }
And i call that function in here
// Prepare validator and input mask QValidator * validator = nullptr; QString inputMask; MainWindow::prepareInputMaskAndValidator(typeOfColumn, validator, inputMask); // Assignment(=) inside if queries is intentional, do not change it to isEqual(==) // Set the validators if(QDoubleValidator * validatorCastedD = dynamic_cast<QDoubleValidator*>(validator)) lineEdit->setValidator(validatorCastedD); else if(QIntValidator * validatorCastedI = dynamic_cast<QIntValidator*>(validator)) lineEdit->setValidator(validatorCastedI); else lineEdit->setValidator(validator); // Set the input mask lineEdit->setInputMask(inputMask);
I assumed if it is not one of the QDoubleValidator or QIntValidator classes than dynamic cast would fail and returns nullptr and if succesful than returning whatever Validator it is.
But it always fails, no matter its type. As i have never done such a thing before, i can't grasp why it fails.
Thanks in advance for any help
-
It's because you always set it to nullptr:
QValidator * validator = nullptr;
...and before you say "but I set it in
prepareInputMaskAndValidator
... " - no, you didn't ;) You've set a copy of that pointer.
If you want to modify the pointer itself you need to pass it by reference (or a pointer to a pointer):
eithervoid MainWindow::prepareInputMaskAndValidator(const QString &type, QValidator*& validator, QString &inputMask) { ... validator = new /*Whatever*/ ... }
or
void MainWindow::prepareInputMaskAndValidator(const QString &type, QValidator** validator, QString &inputMask) { ... if(validator) *validator = new /*Whatever*/ ... }
-
@Chris-Kawa Thank you so much. It seems i had the idea of pointer not being a copy but reference alike. Going to fix it quick.
-
The thing the pointer points to is not copied but the pointer itself (the variable) is.
-
@Chris-Kawa Yeah i realized my mistake, i copied the pointer and then changed its location. Which ended up in originally created pointer to still being nullptr.