QListWidget->clear() throws std::bad_alloc



  • I am currently using a QListWidget in my main window, which displays a list of all the levels my program generates (Level 1, Level 2, etc). If I run my program as normal and keep pressing the "Generate" button without doing anything else then my program will work perfectly fine, it will keep generating levels and updating the QListWidget as it should.

    However, If I Select one of the items in the QListWidget by clicking on it, and THEN hit the "Generate" button, my program will crash and throw a bad_alloc. After doing some debugging I found that it throws the bad_alloc when trying to execute QListWidget->clear(). I have absolutely no idea why this would be happening, has anyone seen this before?

    void MainWindow::on_generateButton_released()
    {
        Generator.clearVectors();
        ui->list_LevelSet->clear(); //std::bad_alloc here
        Generator.generateLevel();
    }
    

    Thanks!


  • Lifetime Qt Champion

    Hi,

    Does your QListWidget contain coming from Generator ?



  • Hi there, to add items to my QListWidget I have a SIGNAL in my Generator class and a SLOT in my MainWindow Class.
    The Slot function looks like this:

    void MainWindow::addToList(int value){
        ui->list_LevelSet->addItem("Level " + QString::number(value));
        QVariant dataValue(value-1);
        ui->list_LevelSet->item(value-1)->setData(Qt::UserRole, dataValue);
    }
    

    So the QListWidget contains x number of items which have the text "Level x" and each item stores the level number (x) as data.



  • EDIT: Please ignore this post, I've figured out the error. I was originally connecting my QListWidget to a QGraphicsView with the follow connect function

    connect(ui->list_LevelSet, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(displayLevel(QListWidgetItem*)));
    

    However I ended up changing the SIGNAL (and subsequently the displayLevel function) to use

    connect(ui->list_LevelSet, SIGNAL(currentRowChanged(int)), this, SLOT(displayLevel(int)));
    

    so that the QGraphicsView would be changed whenever the List was updated, instead of making the user click on an item to update the QGrapicsView. This meant that when I called Clear(); it would of course change the row, which would in turn attempt to display a level that didn't exist and therefore throw the bad_alloc.

    My new function looks like this:

    void MainWindow::on_generateButton_released()
    {
        display = false;
        Generator.clearVectors();
        ui->list_LevelSet->clear();
        display = true;
        Generator.generateLevel();
    }
    

    and I check if 'display' is set to true before display the level.


  • Lifetime Qt Champion

    IIRC, you can use the blockSignals method to achieve the same effect without the need for an additional flag variable.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.