PDA

View Full Version : Problem with new QTableWidgetItem



danilodsp
16th August 2011, 13:06
An error occurs when running this:

My h:

QTableWidgetItem* itemTable[];

My cpp:

conTable = 0;
var1 = 0;
itemTable[conTable] = new QTableWidgetItem("text1");
ui->tableWidget->setItem(var1,0,itemTable[conTable]);
conTable++;
itemTable[conTable] = new QTableWidgetItem("text2");
ui->tableWidget->setItem(var1,1,itemTable[conTable]);
conTable++;

What's wrong in making a new in QTableWidgetItem?

nix
16th August 2011, 15:03
Normal, your
QTableWidgetItem* itemTable[]; is something equivalent to QTableWidgetItem **itemTable.
But you do the allocation of QTableWidgetItem but not it's address.

Seriously this is C code, use Qt containers instead, look to QVector or QList. Something like
QVector<QTableWidgetItem *> itemTable; should be fine.

danilodsp
17th August 2011, 21:15
I don't understand.

I use the normal QTreeWidgetItem and it works.


itemTree[num] = new QTreeWidgetItem(ui->treeWidget);
itemTree[num]->setText(0,Tag[num]->nome);
num++;

Use vector will be a problem.
I want use as a pointer and create indefinitely to fill a table.

jacks916
17th August 2011, 21:15
you may have to format it more like this so that you can access the item later.



ui.table->setItem( row , 0, new QTableWidgetItem() );
ui.table->item(row , 0 )->setText(QString( "%1" ).arg( num ) );
ui.table->item(row, 0 )->setBackgroundColor( QColor(178,34,34) );


Something I found out after hours of invalid pointer access

danilodsp
18th August 2011, 00:11
Perfect.
That's what I needed.

Thanks.

ChrisW67
18th August 2011, 00:59
Where do you allocate space to hold the array of QTableWidgetItem pointers? If you never do that then this a recipe for serious crashing. Using a QList<QTableWidgetItem*> or QVector<QTableWidgetItem*> is a far safer option.

jacks916
18th August 2011, 14:00
Chris was that to me?

They get held into the QTableWidget, I just reference them in the row and col of the table ( item( row, col) ), for my application they work fine, no issues, and no risk. They only get replaced when i say so.

ChrisW67
18th August 2011, 23:53
No, it was for the OP.