Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Crashes on Clearing a QTreeWidget



  • Hello I want to clear a QTreeWidget and used

    ui->DeckList->clear(); // DeckList is a QTreeWidget
    

    However the program sometimes crashes.

    I found that after I clicked on this tree it surely crashes. But if I didn't click the tree it won't crash. What's wrong with it?

    I used the following code in the constructor.

    ui->DeckList->setColumnWidth(0, 25);
    ui->DeckList->setColumnWidth(1, 65);
    ui->DeckList->setColumnWidth(2, 140);
    ui->DeckList->header()->setStretchLastSection(true);
    ui->DeckList->setIndentation(0);
    
    QTreeWidgetItem *md = new QTreeWidgetItem(ui->DeckList);
    QTreeWidgetItem *sd = new QTreeWidgetItem(ui->DeckList);
    ui->DeckList->insertTopLevelItem(0, md);
    ui->DeckList->insertTopLevelItem(1, sd);
    md->setText(0, "0");
    sd->setText(0, "0");
    md->setText(1, "MDeck");
    sd->setText(1, "SDeck");
    QFont f;
    f.setBold(true);
    md->setFont(0, f);
    sd->setFont(0, f);
    md->setFont(1, f);
    sd->setFont(1, f);
    md->setTextAlignment(0, Qt::AlignCenter);
    sd->setTextAlignment(0, Qt::AlignCenter);
    md->setTextAlignment(1, Qt::AlignCenter);
    sd->setTextAlignment(1, Qt::AlignCenter);

  • Lifetime Qt Champion

    Hi
    Its not due to clear. ( very unlikely)
    Did you apply event filter or anything like that ?
    Try a small sample. If you can get that to crash with clear. it might be a bug
    but mostly like you are saving QTreeWidgetItem * somewhere and access after its deleted.



  • @mrjj said in Crashes on Clearing a QTreeWidget:

    Hi
    Its not due to clear. ( very unlikely)
    Did you apply event filter or anything like that ?
    Try a small sample. If you can get that to crash with clear. it might be a bug
    but mostly like you are saving QTreeWidgetItem * somewhere and access after its deleted.

    But when I was debugging, it always stops at ui->DeckList->clear();

    To be more precise, it stopped at qtreewidget.h
    0_1526290651217_1.PNG

    Oh I think I know the reason. I also used on_DeckList_currentItemChanged. So the current item did change when the whole tree was deleted. But I still need this function. Is there a way to prevent such conflict?
    0_1526290943034_2.PNG


  • Lifetime Qt Champion

    Hi
    you need to check if current is null

    if (!current) return;

    when you clear it, none can be selected and hence its null.



  • @mrjj said in Crashes on Clearing a QTreeWidget:

    Hi
    you need to check if current is null

    if (!current) return;

    when you clear it, none can be selected and hence its null.

    That did help. Thanks!


Log in to reply