Narek
Narek

Reputation: 39881

How to make a column in QTableWidget read only?

I would like to have one column in QTableWidget NOT editable.
In forums I have read a lot about some flags but could not manage to implement.

Upvotes: 76

Views: 98364

Answers (5)

amasoudfam
amasoudfam

Reputation: 99

Use this to make the whole widget read only:

tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

Upvotes: 1

user2923436
user2923436

Reputation: 871

The result of using XOR depends on what the current state is. I'd suggest using

item->setFlags(item->flags() &  ~Qt::ItemIsEditable);

to make sure editing is turned off regardless of the current setting.

Upvotes: 55

Damdidam
Damdidam

Reputation: 21

I came to a better suggestion, just overwrite the cellDoubleClicked signal with a new SLOT. This is, if you want none of the cells to be modified

Upvotes: 2

Tim Hutchison
Tim Hutchison

Reputation: 3633

To apply @Narek's code to rows or columns, simply use a simple for loop and put a condition in to include the flags for rows/columns you do not want to be editable.

The following code reads a csv file into a QTableWidget:

if(!rowOfData.isEmpty()){
for (int x = 0; x < rowOfData.size(); x++)
    {
        rowData = rowOfData.at(x).split(",");
        if(ui->table_Data->rowCount() <= x) ui->table_Data->insertRow(x);
        for (int y = 0; y < rowData.size(); y++)
        {
            QTableWidgetItem *item = new QTableWidgetItem(rowData[y],QTableWidgetItem::Type);
            if( y < 3 ) item->setFlags(item->flags() ^ Qt::ItemIsEditable);   // Only disables the first three columns for editing, but allows the rest of the columns to be edited
            ui->table_Data->setItem(x,y,item);
            ui->table_Data->repaint();
        }
    }
}

Upvotes: 0

Narek
Narek

Reputation: 39881

Insert into the QTableWidget following kind of items:

QTableWidgetItem *item = new QTableWidgetItem();
item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);

Works fine!

EDIT:

QTableWidgetItem *item = new QTableWidgetItem();
item->setFlags(item->flags() ^ Qt::ItemIsEditable);

This is a better solution. Thanks to @priomsrb.

Upvotes: 113

Related Questions