Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - How can I make a particular Column of my QTableView as Non Editable?

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?

Thanks in Advance.

like image 599
New Moon Avatar asked Sep 27 '12 07:09

New Moon


People also ask

How do I make QTableWidget not editable?

item->setFlags(item->flags() & ~Qt::ItemIsEditable); to make sure editing is turned off regardless of the current setting.


4 Answers

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));
}
like image 118
MasterAler Avatar answered Sep 19 '22 23:09

MasterAler


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;
}
like image 20
Закиров Ришат Avatar answered Sep 17 '22 23:09

Закиров Ришат


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

like image 25
Angie Quijano Avatar answered Sep 16 '22 23:09

Angie Quijano


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.

like image 23
SingerOfTheFall Avatar answered Sep 16 '22 23:09

SingerOfTheFall