Properly using QTableWidget and QTableWidgetItem
I am having a QMap through which I iterate. I would like to display the keys and values in my QTableWidget.
Code:
int counter=0;
QMapIterator<QChar,int> iter(ArithmeticCoding::letters_freq);
while(iter.hasNext()){
iter.next();
ui->table->setItem(counter,0,item0);
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.
Re: Properly using QTableWidget and QTableWidgetItem
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 to get a pointer to the QTableWidgetItem in a row and column.
Anyway, do you actually get random (garbage) values in the table?
1 Attachment(s)
Re: Properly using QTableWidget and QTableWidgetItem
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:
Attachment 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 :)
Re: Properly using QTableWidget and QTableWidgetItem
You need to pass a QString there, use the static number to convert an int to QString and most likely you will need toInt too (to convert from QString to int).
so use this code:
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
Re: Properly using QTableWidget and QTableWidgetItem
Thanks, this also worked!