I'm using the following code to add a row to a QTableWidget.
QTableWidgetItem *item = new QTableWidgetItem(fileName);
item->setCheckState(Qt::Checked);
QComboBox *cmb = new QComboBox(this->list);
cmb->addItem("one");
cmb->addItem("two");
this->list->setRowCount(this->list->rowCount()+1);
this->list->setItem(this->list->rowCount()-1,0,item);
this->list->setCellWidget(this->list->rowCount()-1,1,cmb);
There are 2 columns in the table. 'item' is placed in the first one, 'cmb' in the second one. Using this code I can succesfully add 1 row to the table, but when I try to add a second row, I get a segmentation 开发者_JS百科fault. It crashes on the this->list->setItem() call.
Any idea of why it crashes?
Thanks!
I can't tell why your code doesn't work as is, but do this:
int N = list->rowCount(); //The problem may lie in multiple rowCount() calls somehow
list->insertRow(N);
list->setItem(N,0,item);
list->setCellWidget(N,1,cmb);
Also, is there a particular reason you use 'this->'? It's generally completely redundant in this situation.
I had code that was extremely similar to you and it crashed as well...
QTableWidgetItem* columnOne = new QTableWidgetItem();
columnOne->setCheckState(Qt::Checked);
QTableWidgetItem* columnTwo = new QTableWidgetItem("Some Text");
int row = tableWidget->rowCount();
tableWidget->insertRow(row);
tableWidget->setItem(row, 0, columnOne);
tableWidget->setItem(row, 1, columnTwo);
However, if I changed the order of the setItem calls so that the check state is added last then it worked. So this is code worked...
QTableWidgetItem* columnOne = new QTableWidgetItem();
columnOne->setCheckState(Qt::Checked);
QTableWidgetItem* columnTwo = new QTableWidgetItem("Some Text");
int row = tableWidget->rowCount();
tableWidget->insertRow(row);
tableWidget->setItem(row, 1, columnTwo);
tableWidget->setItem(row, 0, columnOne);
Problem is in this row (you named some list and QTableWidget the same: "list"):
this->list->setRowCount(this->list->rowCount()+1)
this->list->rowCount()+1
will always return 0+1=1, so that is why you can add first, but not second row to your table.
Solution: name your QTableWidget other than "list", for example:
this->myTableWidget->setRowCount(this->list->rowCount()+1);
this->myTableWidget->setItem(this->list->rowCount()-1,0,item);
this->myTableWidget->setCellWidget(this->list->rowCount()-1,1,cmb);
This issue in my code was happened because of logic in cellChanged SLOT. I was trying to setText in QTableWidget that hasn't been actually created yet.
精彩评论