I have a QTableWidget and an object of class product called p
.
I wanna add items to this table.
I tried the code below but no use.
void MainWindow:: add_to_basket (product p){
ui->tableWidget->insertRow(1);
QLineEdit *qle=new QLineEdit();
qle->setText(p.get_name());
ui->tableWidget->setCellWidget(1,1,qle);
QLineEdit *qle1=new QLineEdit();
qle1->setText(QString::number(p.get_price()));
ui->tableWidget->setCellWidget(1,2,qle1);
QSpinBox *qsb=new QSpinBox();
qsb->setValue(p.get_count());
ui->tableWidget->setCellWidget(1,3,qsb);
}
what should I do?
QTableWidget
should have defined rowCount
and columnCount
properties. It can be done either via QTableWidget
constructor (https://doc.qt.io/qt-5/qtablewidget.html#QTableWidget-1) or via appropriate methods (setRowCounts
and setColumnCounts
). If it is done already, that's great.insertRow
inserts an empty row into the table at given position. ui->tableWidget->insertRow(1)
would insert a new row at position 1
only if you have previously defined rowCount
and columnCount
(see point 1).QSpinBox
is attempted to be put into third column) and insert new product always at first row, your code with point 1 fullfilled will be work fine. But, if your idea is to add a new row each time new product
is added, you should rather call ui->tableWidget->insertRow(tableWidget->rowCount())
and use that value to address appropriate row.You may also want to have a look here for example how to setup QTableWidget
: https://wiki.qt.io/How_to_Use_QTableWidget