2011-03-26 22 views
0

我正在使用以下代碼將一行添加到QTableWidget。QTableWidget setItem()使用Qt的段錯誤

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); 

表中有2列。 'item'放在第一個'cmb'中。使用這段代碼,我可以成功向表中添加1行,但是當我嘗試添加第二行時,出現段錯誤。 它在this-> list-> setItem()調用中崩潰。

任何想法爲什麼它崩潰?

謝謝!

+0

試過你的代碼,它適用於我;沒有分段錯誤向表格窗口小部件添加多於1行的內容。我使用的是Ubuntu 10.10 Qt 4.7.1 – 2011-03-27 01:19:46

回答

0

我不知道爲什麼你的代碼不作爲是工作,但做到這一點:

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); 

此外,有沒有使用「這個 - >」特別的原因?在這種情況下通常是完全多餘的。

+0

我只是用這個 - >因爲我認爲它更清晰..。 我現在通過使用setCellWidget兩次解決了它,並刪除了setItem .. – r1234 2011-03-27 08:34:14

0

我的代碼,這是非常相似的,你和它碰撞,以及...

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); 

但是,如果我改變了setItem調用的順序,使其工作的檢查狀態添加最後再。因此,這是代碼工作...

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); 
0

問題是此行中(你被點名了一些清單,QTableWidget的一樣: 「列表」):

這個 - >列表 - > setRowCount (這 - >列表 - > rowCount時()+ 1)

this->list->rowCount()+1總是返回0 + 1 = 1,所以這就是爲什麼你可以添加第一而不是第二行到您的表。

解決方案:名稱不是 「名單」 之外的其他QTableWidget的,例如:

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); 
0

這個問題在我的代碼中發生,因爲在cellChanged SLOT邏輯。我試圖在QTableWidget中設置尚未實際創建的文本。