QTableWidge 动态插入多行,解决setRowCount方式导致QTableWidgetItem崩溃问题

QTableWidget 先初始化

错误方式: 
 int row    = 10;
 int colunm = 8;
 ui->tableWidget->setRowCount(row);
 ui->tableWidget->setColumnCount(colunm);

   当我们动态添加数据的超过我们设置的行数时候,往往我们会通过 ui->tableWidget->setRowCount(row) 方式来增加行数,但是这样缺导致,我们在自定义widget时候,导致引用崩溃。如:ui->tableWidget->setCellWidget(m_row, 7, myWidget);

 

正确方式:

 int row = 0;
 int colunm = 8;
 ui->tableWidget->setRowCount(row);
 ui->tableWidget->setColumnCount(colunm);

// 插入新行函数  *********************************
void WechatForm::onAddRowData(const GroupInfo data)
{    
    int row = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(row);
    for (int col =0; col <7; col++)
    {
        QString strText = "";
        QTableWidgetItem *item = new QTableWidgetItem();
        item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        switch(col)
        {
        case 0:
            {               
                item->setIcon(QIcon(":/image/image32.png"));               
                item->setTextAlignment(Qt::AlignLeft|Qt::AlignVCenter);               
                item->setCheckState(Qt::Unchecked);               
                strText = data.Name;               
                break;            
            }        
        case 3: strText = tr("待更新"); break;        
        }        
        item->setText(strText);        
        ui->tableWidget->setItem(row , col, item);    
     }    
    WechtItemSelectedForm *deal = new WechtItemSelectedForm(this, ui->tableWidget);    
    QTableWidgetItem *item = ui->tableWidget->item(row , 0);     
    deal->onSetValue(m_mapGroupHistory, data, item);    
    ui->tableWidget_Qun->setCellWidget(row , 7, deal);
}

你可能感兴趣的:(QTableWidge 动态插入多行,解决setRowCount方式导致QTableWidgetItem崩溃问题)