There is a delete button when pressed, which deletes the selected line. If there is more than one row in the table, then there are no problems with deletion, but when the last row remains, it crashes (see photo of the error). Flies to ui.table->removeRow(oldRow); while debugging oldRow = 0 and even tried to insert currentRow () instead of it, but the same error occurs.

 //Находим ΠΏΠΎΠ·ΠΈΡ†ΠΈΡŽ удаляСмой записи int oldRow = ui.table->currentRow(); //УдаляСм строку с записью ΠΈΠ· Π±Ρ€Π°ΡƒΠ·Π΅Ρ€Π° QTableWidgetItem *it; it = ui.table->takeItem(oldRow, 0); it = ui.table->takeItem(oldRow, 1); delete it; ui.table->removeRow(oldRow); 

tried even like that

 //Находим ΠΏΠΎΠ·ΠΈΡ†ΠΈΡŽ удаляСмой записи int oldRow = ui.table->currentRow(); //УдаляСм строку с записью ΠΈΠ· Π±Ρ€Π°ΡƒΠ·Π΅Ρ€Π° ui.table->removeRow(oldRow); 

enter image description here

  • ui is not an object, but a pointer to the window ... - AR Hovsepyan

2 answers 2

The solution is as follows

 if(oldRow==0 && count == 1) //ΡƒΠ±ΠΈΡ€Π°Π΅ΠΌ Π²Ρ‹Π΄Π΅Π»Π΅Π½ΠΈΠ΅ строки ui.table->selectionModel()->clearSelection(); //удаляСм строку ui.table->removeRow(oldRow); 

The fact is that for some reason, when a single line in the table is selected, it gives an error when trying to delete it. When it is not selected, there are no errors. I suppose that when the line is the only one selected, it searches for which other line to select and gets -1, which gives an error.

  • Not a good solution for me. Before deleting, it is necessary to check whether the index of the deleted row falls within the correct limits ( >=0 && < rowCount() ) and then either delete or do something else, according to the situation. - Bearded Beaver

I do not know why your option does not work, it is possible that at the time of the call to removeRow there are no rows in the table for some reason. Check it in the debugger.

If this is not the case, this option should work:

 if(ui.table->rowCount() <= 1) ui.table->setRowCount(0); else ui.table->removeRow(ui.table->currentRow()) 
  • I tried this option earlier and now. On the row ui.table-> setRowCount (0); he falls. That is, it falls when you set the number of rows to zero. Tried even when there are a lot of lists and when you click the delete button, ui.table-> setRowCount (0) is called; but still crashes. - Vova Sazonov
  • Noticed the following: When the line is not selected - deletes. When selected, it gives an error. - Vova Sazonov