QTableView - not allow user to edit cell
-
19-09-2019 - |
Question
I created a QTableView with a QSqlTableModel. By standard, double-clicking on the cells will mark them and the user can edit them. I want, that the user isn't allowed to do that. He is allowed to mark the whole row by clicking on a single cell, but not to edit the cell. How can I do that?
Solution
Depending on whether you are coding everything or doing things in the designer, set
editTriggers
toQAbstractItemView::NoEditTriggers
selectionBehavior
toQAbstractItemView::SelectRows
- optionally set
selectionMode
toQAbstractItemView::SingleSelection
if you want the user to select exactly one row
on the tableview object the appropriate calls will all be prefixed with set
e.g setEditTriggers()
in the Designer you can find these option in the AbstractItemView
section
OTHER TIPS
Try this:
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
Toggle off the table item's ItemIsEditable
bit. e.g.:
QTableWidgetItem* item = new QTableWidgetItem(...);
...
item->setFlags(item->flags() &= ~Qt::ItemIsEditable);
Ideally you will want to use:
void QAbstractItemView::setItemDelegate ( QAbstractItemDelegate * delegate )
And then create a class that inherits from QItemDelegate
like in this example.
Editing your class to have
QWidget * QItemDelegate::createEditor ( QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index ) const
return NULL
or use:
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
You will also want to look at
void setSelectionBehavior ( QAbstractItemView::SelectionBehavior behavior )
With the parameter: QAbstractItemView::SelectRows
For reference: http://doc.trolltech.com/4.5/qtableview.html