QListWidget crash when reusing the widget associated with item

  • I have a custom simple widget inheriting from QWidget and I add it to a QListWidget like this :

    void MainWindow::AddToWidgetList(const QString &tag, const QString &html)
        HtmlItem *html_item = new HtmlItem();
        connect(html_item, SIGNAL(RemoveIt(uintptr_t)), this, SLOT(on_RmBtn_clicked(uintptr_t)));
        QListWidgetItem *list_item = new QListWidgetItem();
        ui->CodeBlocks->setItemWidget(list_item, html_item);

    I then want to move the selected element up when a button is pressed

    void MainWindow::on_UpArrowBtn_clicked()
        if (ui->CodeBlocks->count() < 2)
        int current_row = ui->CodeBlocks->currentRow();
        if (current_row == 0)
        HtmlItem *item_widget = (HtmlItem*)ui->CodeBlocks->itemWidget(ui->CodeBlocks->item(current_row));
        QListWidgetItem *item = ui->CodeBlocks->takeItem(current_row);
        ui->CodeBlocks->insertItem(current_row - 1, item);
        ui->CodeBlocks->setItemWidget(item, item_widget);

    but I get crash in this line :

    ui->CodeBlocks->setItemWidget(item, item_widget);

  • Lifetime Qt Champion

    @developer-123-0 said in QListWidget crash when reusing the widget associated with item:

    but I get crash in this line

    what kind of crash is that? Did you already debug to see what happens?
    Is item_widget a valid pointer?
    After this line you do not check the pointer:

    HtmlItem *item_widget = (HtmlItem*)ui->CodeBlocks->itemWidget(ui->CodeBlocks->item(current_row));

Log in to reply