PDA

View Full Version : Properly using QTableWidget and QTableWidgetItem



c0dehunter
27th October 2012, 10:35
I am having a QMap through which I iterate. I would like to display the keys and values in my QTableWidget.



int counter=0;
QMapIterator<QChar,int> iter(ArithmeticCoding::letters_freq);
while(iter.hasNext()){
iter.next();
QTableWidgetItem *item0=new QTableWidgetItem(iter.key());
ui->table->setItem(counter,0,item0);

QTableWidgetItem *item1=new QTableWidgetItem(iter.value());
ui->table->setItem(counter,1,item1);
counter++;
}

Of course here my pointers to QTableWidgetItem get lost resulting in random garbage in my table. What would be the proper way of using them? Should I save them to an additional array? That seems like an overhead to me.

Zlatomir
27th October 2012, 14:10
What do you mean "get lost"? You allocate on the heap and the table take ownership of them. To use those later you use QTableWidget::item (http://doc.qt.digia.com/qt/qtablewidget.html#item) to get a pointer to the QTableWidgetItem in a row and column.

Anyway, do you actually get random (garbage) values in the table?

c0dehunter
27th October 2012, 15:17
Zlatomir thanks for answering.

Your point about table taking ownership is correct, thanks for explaining. However, yes, I get random string garbage in in second cell (for iter.value()). Specifically, I get text from labels on my window instead of QMap values. Yes, strange. I've debugged and the values in QMap are correct so I was guessing something has to be wrong with pointers. A screenshot:

8374



If I put in some string to second QTableWidgetItem it displays it well. Also, I've tested the iter.value() values (qDebug() << iter.value();) and they are correct. Maybe I have to cast int to String in some special way?

** MAJOR EDIT:
I was able to fill the second cell properly using
QTableWidgetItem *item1=new QTableWidgetItem(tr("%1").arg(iter.value()));

Why Did I have to do this it's still a mystery to me :)

Zlatomir
27th October 2012, 15:35
You need to pass a QString there, use the static number (http://qt-project.org/doc/qt-4.8/qstring.html#number) to convert an int to QString and most likely you will need toInt (http://qt-project.org/doc/qt-4.8/qstring.html#toInt) too (to convert from QString to int).
so use this code:


//...
QTableWidgetItem *item1=new QTableWidgetItem( QString::number(iter.value()) );

The problem seems to be that integet, because the QTableWidget has an constructor that takes an int as some "type" (i don't know what that means): doc link (http://doc.qt.digia.com/latest/qtablewidgetitem.html#QTableWidgetItem)

c0dehunter
27th October 2012, 15:38
Thanks, this also worked!