Forbid caracters which aren't numerical in a QStandardItemModel
there's any tool which allow to forbid the use of caracters which aren't numerical in a QStandardModel? Or a tool which has a similar purpose? I looked the doc but didn't find what i mean.
GentooXativa last edited by
Try to use "QRegExp":http://qt-project.org/doc/qt-4.8/qregexp.html
The problem is that the model will only get the modified text when the editor indicates that it's done. It would suprise users if the alphanumerical characters would suddenly disapear, i think. Instead, perhaps you should solve the issue at the delegate level: the level that presents the editor for the data.
Thanks you, i will try
At the delegate, you should reimplement the createEditor method, return a [[Doc:QLineEdit]] (if that's the correct widget) and add a [[Doc:QValidator]] subclass to the line edit. That prevents the user from entering the wrong characters at all. l would start with a [[Doc:QRegExpValidator]].
thanks you for your help, I reimplemented the createEditor method :
QWidget* MyView::MyDelegate::createEditor ( QWidget * parent,
const QStyleOptionViewItem & option,
const QModelIndex & index ) const
QLineEdit* lineEdit = new QLineEdit(parent);
QRegExp regex = QRegExp(QString::fromStdString("\d+"));
lineEdit->setValidator(new QRegExpValidator(regex, NULL));
It works perfectly when the cell is empty, i.e I can't write characters no-numerical but if the cell contains anything and I try to edit it, I can write alphanumerical characters. I don't understand what happened ! Does the setItem() method modify the delegate?
[Edit: Cleaned up code formatting; mlong]
QRegExp regex = QRegExp(QString::fromStdString("^\d+$"));
As it currently stands, 345X123Y still matches the regexp because it matches the substrings 345 and 123. But by putting the ^ and $ anchors into the regexp, it will force the regexp to match an entire string of nothing but digits.
Unfortunately, the problem still the same :
- if I edit an empty cell, I can't put any alphabetic character
- but if I try to modify a full cell I can !
I don't understand. Perhaps the number setted in the cell by the setItem method is not considered to match the regex and it's why the delegate doesn't react.
The validators only validate against manually-entered data (see the note "here":/doc/qt-4.8/qlineedit.html#text-prop .) If you want to filter anything that is being programatically entered, you'll need to check that data itself before you try to set it.
But I set data in my program and they are numerical. I don't understand why when I try to edit one I can write alphabetic characters. In this case, the validator doesn't work correctly.