QListView & QStandardItemModel check text before editing row

2.1k views Asked by At

I want to check the text of a row in QListView before the user is editing it. If it doesn't fit a pattern, I don't want to accept it.

Currently I have a QListView and QStandardItemModel. I can easily add and remove items via the QStandardItemModel. I also set the model of the list view.

Are there some delegates or event function(s) on the list or the model for editing?

2

There are 2 answers

3
4pie0 On BEST ANSWER

you can overload data() and setData() functions from QStandardItemModel, then when user tries to edit item your setData will be called with Qt::EditRole and there you can do your processing.

http://qt-project.org/doc/qt-5.0/qtcore/qabstractitemmodel.html#setData

2
Chris On

If I understand you correctly, you want to check the value of an item at the time the user attempts to enter the edit mode?

Using a delegate should work for this fairly well:

class MyItemDelegate : public QItemDelegate {
    public:
        QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
            if(index.data() == /* do whatever check you want here */) {
                return NULL; // Prevent editing
            }
            return QItemDelegate::createEditor(parent, option, index);
        }
};

listView->setItemDelegate(new MyItemDelegate());