PDA

View Full Version : integer as a QTableWidgetItem ?



tommy
29th May 2009, 12:15
I'd like to load QTableWidget with integers and then display selected integers. It seems that QTableWidget can accept integers as shown here:



QTableWidget myTable = new QTableWidget(10, 10, this); //make a 10x10 table

QTableWidgetItem *newItem = new QTableWidgetItem(1); //convert from integer
myTable->setItem(0, 0, newItem); //set object


But how do you visualize a selected entry from this table (entry 0,0)? The below code evidently does not work because the returned type is wrong.



int a = myTable->item(0,0);


I'd have to do this


QTableWidgetItem *a = myTable->item(0,0);


But how can I get my integer out of this? This won't return integer.

Lykurg
29th May 2009, 13:28
int val = -1;
QTableWidgetItem *a = myTable->item(0,0);
if (a)
val = a->text().toInt();


You may also want have a look at QTableWidgetItem::data() and setData woth UserRole...

tommy
29th May 2009, 13:48
This worked great thanks!

How do you empty the QTableWidget memory after you are done using the table and want to get rid of it?

Lykurg
29th May 2009, 13:51
QTableWidget::clear() or QTableWidget::clearContents(). Also frees the memory:

void QTableModel::clearContents()
{
for (int i = 0; i < tableItems.count(); ++i) {
if (tableItems.at(i)) {
tableItems.at(i)->view = 0;
delete tableItems.at(i); // <--
tableItems[i] = 0;
}
}
reset();
}

tommy
29th May 2009, 14:20
Thanks again!

But can I just delete the QTableWidgetItem object? This should free the memory, too. How woud you do that?

Lykurg
29th May 2009, 14:50
But can I just delete the QTableWidgetItem object? This should free the memory, too. How woud you do that?

If you only want to delete a single item which is allready assigned to the table use

QTableWidget::takeItem ( int row, int column )
but be aware that you must delete the returned item yourself!

Example:

QTableWidgetItem *a = myTable->takeItem(0,0);
if (a)
delete a;

tommy
29th May 2009, 16:11
Hi Lykurg,

Unfortunately it didn't work. The below code for some reason always assigns 0 to val. Why doesn't it assign 3 to val?

Thanks!




QTableWidget myTable = new QTableWidget(5, 5, this);

QTableWidgetItem *newItem = new QTableWidgetItem(3);
myTable->setItem(3, 3, newItem);

QTableWidgetItem *a = myTable->item(3,3);
int val = a->text().toInt();

Lykurg
29th May 2009, 18:44
QTableWidgetItem *newItem = new QTableWidgetItem(1); //convert from integer


Why doesn't it assign 3 to val?

because the above statement is wrong. You have to use:

QTableWidgetItem *newItem = new QTableWidgetItem(QString::number(1));