问题
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?
回答1:
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:
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());
来源:https://stackoverflow.com/questions/18470445/qlistview-qstandarditemmodel-check-text-before-editing-row