http://blog.csdn.net/leftover_crazy/article/details/5777890
实例化QTabWidget 后需要做如下设置
- QStringList headers;
- headers<<"产品名称(加工方式)"<<"产品型号"<<"产品规格"<<"加工备注"<<"产品单位"<<"产品单价"<<"产品数量"<<"金额";
- ui->tableWidget->setColumnCount(8);
- ui->tableWidget->setRowCount(0);
- ui->tableWidget->setHorizontalHeaderLabels(headers);
- ui->tableWidget->resizeColumnsToContents();
接着下来是常用的表格操作
插入行操作
- int row=ui->tableWidget->rowCount();
-
-
- ui->tableWidget->insertRow(row);
-
-
-
- ui->tableWidget->setItem(row,0,new QTableWidgetItem(ui->comboBox_8->currentText()));
- ui->tableWidget->setItem(row,1,new QTableWidgetItem(ui->lineEdit_5->text().trimmed()));
- ui->tableWidget->setItem(row,2,new QTableWidgetItem(ui->comboBox_9->currentText()));
- ui->tableWidget->setItem(row,3,new QTableWidgetItem(tr("")));
- ui->tableWidget->setItem(row,4,new QTableWidgetItem(ui->comboBox_10->currentText()));
- ui->tableWidget->setItem(row,5,new QTableWidgetItem(ui->lineEdit_9->text().trimmed()));
- ui->tableWidget->setItem(row,6,new QTableWidgetItem(ui->lineEdit_10->text().trimmed()));
- ui->tableWidget->setItem(row,7,new QTableWidgetItem(ui->lineEdit_11->text().trimmed()));
获取表格内的某个item数据
- currentrow=ui->tableWidget->currentIndex().row();
- currentcolumn=ui->tableWidget->currentIndex().column();
-
- currentrow=ui->tableWidget->currentRow();
- currentcolumn=ui->tableWidget->currentColumn();
-
- QString Itemstring=ui->tableWidget->item(currentrow,1)->text();
然后就可以使用setitem进行数据修改
删除某一列 或者删除某一行
- ui->tableWidget->removeRow(currentrow);
- ui->tableWidget->removeColumn(x);
QTabWidget 使用的时候如果读取的数据不存在 或者读取的数据项在setitem的时候没有写入数据,则程序会崩溃
比如:
-
- ui->tableWidget->setItem(row,1,new QTableWidgetItem(ui->tableWidget->item(currentrow,1)->text()));
- ui->tableWidget->setItem(row,2,new QTableWidgetItem(ui->comboBox_7->currentText()));
- ui->tableWidget->setItem(row,3,new QTableWidgetItem(ui->lineEdit_13->text().trimmed()));
- ui->tableWidget->setItem(row,4,new QTableWidgetItem(ui->comboBox_11->currentText()));
- ui->tableWidget->setItem(row,5,new QTableWidgetItem(ui->lineEdit_15->text().trimmed()));
- ui->tableWidget->setItem(row,6,new QTableWidgetItem(ui->lineEdit_4->text().trimmed()));
- ui->tableWidget->setItem(row,7,new QTableWidgetItem(ui->lineEdit_19->text().trimmed()));
- ui->tableWidget->setItem(row,8,new QTableWidgetItem(ui->lineEdit_12->text().trimmed()));
这里我们将某一行的第一列数据的setitem函数注释掉
在添加数据的时候index指向的数据项将为空,但是这里的为空并非想象中的空字符串""
当我们读取数据的时候
- ui->lineEdit_19->setText(ui->tableWidget->item(currentrow,0)->text());
此时程序编译链接正常通过,但是程序运行时将会导致调用栈出错,找不到该index指向的数据的地址