Reputation: 639
I populated a QTreeWidget with some data.The first column of each row is an integer value. When I press delete on a selected Item I would like that item to disappear and the numbers after the deleted item to decrease with 1. For example if I have 5 items in my first column I have the labels 1,2,3,4,5. When I delete item 3 for example I would like my new labels to be 1,2,3,4. Now my labels are 1,2,4,5.I have tried several things but did not find a good solution... My code is given bellow
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Delete)
{
QTreeWidgetItem *item = this->ui->testResultsTW->currentItem();
if(!item)return;
int x = this->ui->testResultsTW->indexOfTopLevelItem(item);
if(x >= 0 && x < this->ui->testResultsTW->topLevelItemCount())
{
item = this->ui->testResultsTW->takeTopLevelItem(x);
if(item)
{
delete item;
stringstream ss;
ss << (x + 1);
string message = "Item " + ss.str() + " has been deleted";
QTreeWidgetItem *item2;
for(int i = x; i <= this->ui->testResultsTW->topLevelItemCount() ; i++)
{
item2 = this->ui->testResultsTW->takeTopLevelItem(i);
ss << (i - 1);
string nr = ss.str();
item2->data(0,Qt::UserRole) = nr;
// item2->data(0,Qt::UserRole) = nr.c_str();
// item2->setText(0,tr("Ana"));
}
QMessageBox::information(this,"Deleted",message.c_str());
}
}
}
}
Upvotes: 0
Views: 1367
Reputation: 2668
You should set the text on the column 0 manually.
if(event->key() == Qt::Key_Delete)
{
QTreeWidgetItem *item = this->ui->testResultsTW->currentItem();
if(!item)return;
int x = this->ui->testResultsTW->indexOfTopLevelItem(item);
if(x >= 0 && x < this->ui->testResultsTW->topLevelItemCount())
{
item = this->ui->testResultsTW->takeTopLevelItem(x);
if(item)
{
delete item;
stringstream ss;
ss << (x + 1);
string message = "Item " + ss.str() + " has been deleted";
for(int i = x; i <= this->ui->testResultsTW->topLevelItemCount() ; i++)
{
QTreeWidgetItem *topItem = this->ui->topLevelItem(i);
if(topItem)
{
topItem->setText(0, QString::number(i + 1));
}
}
QMessageBox::information(this,"Deleted",message.c_str());
}
}
}
Another question is :
item2 = this->ui->testResultsTW->takeTopLevelItem(i);
This code is remove item from the tree view, do you really want to remove it?
Upvotes: 1