Validating user input in QTableView

I have a QTableView and I want to check user input. If the user inserts an invalid value into the QTableView cell, I want to select that cell and disable QPushButton .

How can i achieve this? Can QValidator use QValidator ?

+6
source share
1 answer

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" //... ItemDelegate *itDelegate = new ItemDelegate; ui->tableView->setItemDelegate(itDelegate); 

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";//do something } else { model->setData(index, data); } } 

But in this case, do not forget to delete the line editor->setValidator(new QIntValidator); from your code

+9
source

Source: https://habr.com/ru/post/977367/


All Articles