Qt - How can I make a particular Column of my QTableView as Non Editable?
Solution 1
You can use the setItemDelegateForColumn()
function. Implement a read-only delegate, and set it for the column you need.
You can also use the flags inside your model, and remove the Qt::ItemIsEditable
flag for a specific column.
Solution 2
Something like that may also do it:
class NotEditableDelegate : public QItemDelegate
{
Q_OBJECT
public:
explicit NotEditableDelegate(QObject *parent = 0)
: QItemDelegate(parent)
{}
protected:
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{ return false; }
QWidget* createEditor(QWidget *, const QStyleOptionViewItem &, const QModelIndex &) const
{ return Q_NULLPTR; }
};
In use:
// Make all the columns except the second read only
for(int c = 0; c < view->model()->columnCount(); c++)
{
if(c != 1)
view->setItemDelegateForColumn(c, new NotEditableDelegate(view));
}
Solution 3
The easiest way is settting the flag of the item you don't want to be editable in this way:
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
You can also check this thread: Qt How to make a column in QTableWidget read only
Solution 4
You need to override the 'flags' method and specify the editability parameters of the element for the selected column
Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return Qt::NoItemFlags;
if(index.column() == SELECTED_COLUMN_NUM)
{
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
New Moon
Updated on June 15, 2022Comments
-
New Moon about 2 years
I have a
QTableView
with 4 Rows and 4 columns each representing their data's in it. By default theQTableView
is editable. Now I want to make any particular column as non editable in myQTableView
.How can I do it?
Thanks in Advance.
-
Charl Botha about 11 yearsWow, that's the cleanest solution I've seen up to now, especially if you only want the data to be read-only in one of your views on the same model. Thanks!
-
Matt Phillips about 10 yearsBut how can this method be applied to a single column or row, as OP asks?
-
Michał Walenciak over 9 yearsI guess you meant overriding
bool QAbstractItemView::edit(const QModelIndex & index, EditTrigger trigger, QEvent * event)
didn't you? In such case you can just returnfalse
for read-only column. -
ricekab over 4 yearsRetrurning true instead of false in editorEvent will prevent createEditor from being called at all, as it consumes the event at that point.
-
mike rodent almost 3 years@ricekab I'm not sure that is true: the doc says "The base implementation returns false (indicating that it has not handled the event)." and according to an experiment I just did returning false for a given
index.colum()
did not stop the editing. -
Soren Stoutner about 2 yearsThis method works for QTableWidges, but not for QTableViews, which is what the question is asking about.