Łukasz Przeniosło
Łukasz Przeniosło

Reputation: 2959

QtableView set whole row as readonly

I am having problems setting the whole row of a QTableView to read only. When I use setEnabled method it only makes the first column readonly. Here is an example, I am adding a new row to the table and trying to make the whole row readonly:

void CItemsMenu::addSlave(const quint8 addr, const QString& uniqId, const QString& userString)
{
    // create new item
    QStandardItem* item = new QStandardItem(m_columnLabels.size()); // size is 3

    // make item readonly
    item->setEditable(false); // this makes only the 1st column readonly

    // append new item
    mp_itemsModel->appendRow(item);
    int row = mp_itemsModel->rowCount() - 1;

    // slave address
    mp_itemsModel->setData(mp_itemsModel->index(
                                 row, (int)itemsTableCol::slaveAddr, QModelIndex()), addr, Qt::EditRole);

    // unique ID
    mp_itemsModel->setData(mp_itemsModel->index(
                                 row, (int)itemsTableCol::uniqId, QModelIndex()), uniqId, Qt::EditRole);

    // user string
    mp_itemsModel->setData(mp_itemsModel->index(
                                 row, (int)itemsTableCol::userStr, QModelIndex()), userString, Qt::EditRole);
}

I would appreciate all help.

Edit: solution:

QList<QStandardItem*> itemsList;
for (int i = 0; i < m_columnLabels.size(); i++)
{
     itemsList.append(new QStandardItem(1));
     itemsList.last()->setEditable(false);
}

Upvotes: 0

Views: 1637

Answers (1)

Benjamin T
Benjamin T

Reputation: 8321

You need one item per cell.

When you call:

mp_itemsModel->appendRow(item);

you only set the item for the first column. Quoting Qt documentation:

When building a list or a tree that has only one column, this function provides a convenient way to append a single new item.

When dealing with a QTableView you should be calling the overload of appendRow() that takes a QList<QStandardItem *>. Like this:

QList<QStandardItem *> list;
... // Fill list and set all items in the list to be read-only.
mp_itemsModel->appendRow(list);

Upvotes: 1

Related Questions