Reputation: 13
I have this signal on QPushButton:
void MainWindow::on_addNode_clicked()
{
ui->nodesTable->insertRow(ui->nodesTable->rowCount());
if(ui->nodesTable->rowCount()>1)
{
ui->nodesTable->item(ui->nodesTable->rowCount()-1, 0)->setText(ui->nodesTable->item(ui->nodesTable->rowCount()-2,0)->text());
}
else
{
ui->nodesTable->item(ui->nodesTable->rowCount()-1, 0)->setText(QString::fromStdString("0"));
}
}
But it crashes with segmentation fault each time when I click the button. As I understood, item(...) give nullptr but why?
Upvotes: 1
Views: 1394
Reputation: 330
You have to set the column count and you must set the item manually:
ui->nodesTable->setColumnCount(1);
ui->nodesTable->insertRow(ui->nodesTable->rowCount());
ui->nodesTable->setItem(ui->nodesTable->rowCount()-1, 0, new QTableWidgetItem("0") );
if(ui->nodesTable->rowCount()>1)
{
ui->nodesTable->item(ui->nodesTable->rowCount()-1, 0)->setText(ui->nodesTable->item(ui->nodesTable->rowCount()-2,0)->text());
}
else
{
ui->nodesTable->item(ui->nodesTable->rowCount()-1, 0)->setText(QString::fromStdString("0"));
}
Upvotes: 0
Reputation: 344
at the first time there is no item in your table, your application crashed if pointer pointed non and when you want to reach it!
try this;
void MainWindow::on_addNode_clicked()
{
ui->nodesTable->insertRow(ui->nodesTable->rowCount());
if( !ui->nodesTable->rowCount() )
{
ui->nodesTable->item(ui->nodesTable->rowCount()-1, 0)->setText(ui->nodesTable->item(ui->nodesTable->rowCount()-2,0)->text());
}
else
{
ui->nodesTable->setItem(0, 0,new QTableWidgetItem(QString("New Item")));
}
}
Upvotes: 0
Reputation: 2192
Since you didn’t specify the number of rows and columns your QTableWidget
starts with 0 rows and 0 columns, adding 1 row still leaves you with 0 columns.
Additionally you have to create your items first via setItem
before you can access them via item
Please take a look at the overview in the docs.
On another note:
In the else
branch of your if (ui->nodesTable->rowCount() > 1)
rowCount() == 0
and therefore you access ui->nodesTable->item(-1, 0)
which is out of bounds.
Upvotes: 2