PDA

View Full Version : Creatin an editable array



Glouglou
1st July 2012, 20:38
Hi,

First of all, english isn't my mothertongue so I want to apologize for any mistake that could be present in this post.

I'm kind of new in Qt (I'm using Qt 4.8.2 by the way) and I would like to create an array similar to the QTableView object.
However, I want that each row of the two first column of this array to be editable.

For example, let's say that the user can enter any integer he wants in the two first column and the third one will contain their sum.
The user can't alter the data contained in the third column.

I've searched on the Qt documentation but I didn't found anything that allow to create this kind of array.

Thanks for answering me

mvuori
1st July 2012, 22:05
Perhaps QTableWidget.

With it, you can make parts of the table read-only and others editable, see for example
http://stackoverflow.com/questions/2574115/qt-how-to-make-a-column-in-qtablewidget-read-only

wysota
1st July 2012, 22:54
The most proper approach is to use QTableView and a custom model with reimplemented methods such as QAbstractItemModel::setData() and QAbstractItemModel::flags(). Sum calculation would take place when setData() is called and flags() allow you to control which cells are editable and which are not.

Glouglou
2nd July 2012, 18:21
Hi,

Thanks for your answers,
I used the following code:


void test::disableEdit(QTableWidgetItem* pItem)
{
Qt::ItemFlags eFlags = pItem->flags();
eFlags &= ~Qt::ItemIsEditable;
pItem->setFlags(eFlags);
}

void test::initArray()
{
this->arr = new QTableWidget();
int nrow, ncolumn;
QStringList list;
nrow = 10;
ncolumn = 3;
this->arr->setRowCount(nrow);
this->arr->setColumnCount(ncolumn);
list << "Col 1" << "Col 2" << "Col 3";
this->arr->setHorizontalHeaderLabels(list);
int i = 0;
while (i <= arr->rowCount())
{
QTableWidgetItem *newitem = new QTableWidgetItem();
this->disableEdit(newitem);
this->arr->setItem(i, 2, newitem); // 2 is the number of the column on which I disable edition
++i;
}
}


It works but I have to loop for every column when I want to disable edition which is kind of long.

@wysota: I understand what you said but I have no idea on how to use a custom model and QAbstractItemModel::flags() to control which cells are editable and which are not.
Do you have a link to a tutorial or some simple code sample?

Thanks for your answers.

wysota
2nd July 2012, 22:14
All you need is in the docs. flags() should check the column one is asking about and either include Qt::ItemIsEditable in the return value or not based on whether you want a particular column to be editable or not.