Adding text from line edits to tablewidget
-
The following code is used by me to add text in several lineedits to a tablewidget when button is clicked! Though I am able to add the values to a single row when I fill the lineedits and click the button again the previous row is overridden without getitng a new row
void MainWindow::on_pushButton_2_clicked()
{
int m=1
ui->tableWidget_2->setColumnCount(3);
ui->tableWidget_2->setRowCount(m);ui->tableWidget_2->setItem(m-1, 0, new QTableWidgetItem(ui->lineEdit->text()));
ui->tableWidget_2->setItem(m-1, 1, new QTableWidgetItem(ui->lineEdit_1->text()));
ui->tableWidget_2->setItem(m-1, 2, new QTableWidgetItem(ui->lineEdit_2->text()));
m++;}
here i increment m(number of rows) by 1 inorder to add a new row! But no new row is created only the previous row is overridden! How can I prevent this so that I can add multiplerows? -
Hi,
When u click on button, u will get one row based on condition.
m = 1;
then m value is changed to 2, where the statements wont execute further to add new row.Thanks,
-
@Lasith
What is the point to increment a local variable m (m++;)? It is local and will be initialized to 1 next time on_pushButton_2_clicked() is called.
Use http://doc.qt.io/qt-5/qtablewidget.html#rowCount to get current number of rows and add 1:
void MainWindow::on_pushButton_2_clicked()
{
int m= ui->tableWidget_2->rowCount() + 1;
ui->tableWidget_2->setColumnCount(3);
ui->tableWidget_2->setRowCount(m);ui->tableWidget_2->setItem(m-1, 0, new QTableWidgetItem(ui->lineEdit->text()));
ui->tableWidget_2->setItem(m-1, 1, new QTableWidgetItem(ui->lineEdit_1->text()));
ui->tableWidget_2->setItem(m-1, 2, new QTableWidgetItem(ui->lineEdit_2->text()));
}