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

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();
        html_item->set_tag(tag);
        html_item->set_html(html);
        connect(html_item, SIGNAL(RemoveIt(uintptr_t)), this, SLOT(on_RmBtn_clicked(uintptr_t)));
        QListWidgetItem *list_item = new QListWidgetItem();
        html_item->set_list_item(list_item);
        list_item->setSizeHint(html_item->sizeHint());
        ui->CodeBlocks->addItem(list_item);
        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)
            return;
        int current_row = ui->CodeBlocks->currentRow();
        if (current_row == 0)
            return;
        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