PDA

View Full Version : add and delete row dynamically in QTableWidget



SIFE
7th December 2011, 23:35
I have this piece of code:

Store::Store(QWidget *parent) : QMainWindow(parent),
ui(new Ui::Store)
{
// ..
connect(id, SIGNAL(currentIndexChanged(int)), name, SLOT(setCurrentIndex(int)));
connect(name, SIGNAL(currentIndexChanged(int)), id, SLOT(setCurrentIndex(int )));
connect(id, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int )));

connect(ui->billTableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(addRow(int, int)));
}

void Store::addRow(int row, int col)
{
QMessageBox msg;
if (ui->billTableWidget->rowCount() == row + 1)
{
QTableWidgetItem *item = new QTableWidgetItem;
item = ui->billTableWidget->item(row, col);
if ((item->text().length() > 0) || (ui->billTableWidget->currentRow() != 0))
{
QComboBox *name = new QComboBox;
QComboBox *id = new QComboBox;
ui->billTableWidget->insertRow(row + 1);
ui->billTableWidget->setCellWidget(row + 1, 0, id);
ui->billTableWidget->setCellWidget(row + 1, 1, name);

connect(id, SIGNAL(currentIndexChanged(int)), name, SLOT(setCurrentIndex(int)));
connect(name, SIGNAL(currentIndexChanged(int)), id, SLOT(setCurrentIndex(int )));
connect(id, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int )));

PrintBill bill(ui);
bill.getItems(id, name);
}
else
{
ui->billTableWidget->removeCellWidget(row + 1, 0);
ui->billTableWidget->removeCellWidget(row + 1, 1);
ui->billTableWidget->removeRow(ui->billTableWidget->rowCount());
}
}

// msg.exec();

QMessageBox sd;
sd.setText(QString::number(row) + QString::number(col));
//sd.exec();
}
Now, if the user select an item from QComboBox widget (id or name), a new row inserted, but if the user select the first item from QComboBox, witch is an empty item, the last row removed. of course this happen only with the row before the last now. Now, I am facing two problems:
1) I can't delete row.
2) I can only add one more row, the new row one doesn't respond to signal correctly. When I chose new item in the second row, it interpreted it like I am still in the first row.

SIFE
8th December 2011, 07:47
7161
I add an image to make my problem more clear.