PDA

View Full Version : Trying to set numbers in a table but not working.



robgeek
4th April 2015, 16:03
Hi!

I'm trying to show numbers in a QTableWidget, but my following code is showing nothing! There is no compile error. What's going on?

for(int i = 0; i < LINES; i++)
{
for(int j = 0; j < COLS; j++)
{
QTableWidgetItem val( QString::number( 123 ) );//This number is only for test.
ui->tableWidget->setItem(i, j, &val);
}
}

Thanks!

wysota
4th April 2015, 17:36
Create the items on heap and not on the stack.

robgeek
4th April 2015, 18:02
Wut?

I tried this but i get an error message:

QTableWidgetItem val( QString::number( 1 ) );

for(int i = 0; i < LINES; i++)
{
for(int j = 0; j < COLS; j++)
{
val.setText( QString::number( 123 ) );
ui->historicLM->setItem(i, j, &val);
}
}

QTableWidget: cannot insert an item that is already owned by another QTableWidget

stampede
4th April 2015, 21:32
Wut?
http://www.cplusplus.com/reference/new/operator%20new/

anda_skoa
4th April 2015, 21:39
Wut?

As wysota wrote: allocate the items on the heap, not on the stack.

Your "val" instance is stack allocated. The fact that you have to use the address operator to satisfy the signature of setItem() should have been quite a strong hint already.

Cheers,
_

robgeek
4th April 2015, 22:52
But i used "new" and still not working!
Bellow, the entire code.

Test::Test(QWidget *parent) : QDialog( parent ), ui(new Ui::Test)
{
ui->setupUi( this );

ui->tableWidget->setColumnCount( 21 );
QHeaderView *header = ui->tableWidget->horizontalHeader( );
header->resizeSections(QHeaderView::Stretch);

QStringList colsnames("#");
for(int i = 0; i < COLS; i++)
colsnames << QString::number( (i + 1) );

ui->tableWidget->setHorizontalHeaderLabels( colsnames );

for(int i = 0; i < LINES; i++)
{
for(int j = 0; j < COLS; j++)
{
QTableWidgetItem *val = new QTableWidgetItem( QString::number( 123 ) );
ui->tableWidget->setItem(i, j, val);
}
}

}

robgeek
5th April 2015, 02:38
Guys! Problem fixed. All i did was add insertRow method.

for(int i = 0; i < LINES; i++)
{
ui->tableWidget->insertRow( i );
for(int j = 0; j < COLS; j++)
{
QTableWidgetItem *val = new QTableWidgetItem( QString::number( 123 ) );
ui->tableWidget->setItem(i, j, val);
}
}

Now everything is working fine.

Thank you for your help!