I have a QTableView
with 4 Rows and 4 columns each representing their data's in it. By default, the QTableView
is editable. Now, I want to make any particular column as non-editable in my QTableView
.
How can I do it?
I have a QTableView
with 4 Rows and 4 columns each representing their data's in it. By default, the QTableView
is editable. Now, I want to make any particular column as non-editable in my QTableView
.
How can I do it?
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.
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));
}
index.colum()
did not stop the editing. –
Calliope 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
In the overide method just change it to if(!(index.column() == 0)
and change the Flag
value as Flag |= Qt::ItemisEditable
.
This Works Fine.
bool QAbstractItemView::edit(const QModelIndex & index, EditTrigger trigger, QEvent * event)
didn't you? In such case you can just return false
for read-only column. –
Bur 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;
}
May be this late, but for future reference. You should set the table view to NoEditTrigger
like this:
myTableView->setModel(model);
myTableView->setEditTriggers(QAbstractItemView::NoEditTriggers)
© 2022 - 2024 — McMap. All rights reserved.