Yes, you can do this, use a custom QItemDelegate for this purpose (I used the QIntValidator as an example).
Title:
#ifndef ITEMDELEGATE_H #define ITEMDELEGATE_H #include <QItemDelegate> class ItemDelegate : public QItemDelegate { Q_OBJECT public: explicit ItemDelegate(QObject *parent = 0); protected: QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget * editor, const QModelIndex & index) const; void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const; void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const; signals: public slots: }; #endif // ITEMDELEGATE_H
Srr
#include "itemdelegate.h" #include <QLineEdit> #include <QIntValidator> ItemDelegate::ItemDelegate(QObject *parent) : QItemDelegate(parent) { } QWidget *ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QLineEdit *editor = new QLineEdit(parent); editor->setValidator(new QIntValidator); return editor; } void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString value =index.model()->data(index, Qt::EditRole).toString(); QLineEdit *line = static_cast<QLineEdit*>(editor); line->setText(value); } void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QLineEdit *line = static_cast<QLineEdit*>(editor); QString value = line->text(); model->setData(index, value); } void ItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { editor->setGeometry(option.rect); }
Using:
#include "itemdelegate.h"
In this case, the user will not be able to enter incorrect data, but you can use the following:
void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QLineEdit *line = static_cast<QLineEdit*>(editor); QIntValidator validator; int pos = 0; QString data = line->text(); if(validator.validate(data,pos) != QValidator::Acceptable) { qDebug() << "not valid";
But in this case, do not forget to delete the line editor->setValidator(new QIntValidator); from your code