Forbid caracters which aren't numerical in a QStandardItemModel
-
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.
-
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]].
-
Hello,
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));return lineEdit;
}@
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]
-
try
@
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.
-