QTableWidget setItem problem (program crash)



  • Hello.

    I have a problem with QTableWidget, specifically with setItem method.

    My part of the code:

    void MainWindow::on_spinBox_valueChanged(int arg1)
    {
        ui->table->setRowCount(arg1);
    }
    
    void MainWindow::on_table_cellChanged(int row, int column)
    {
        QString dataTxt = ui->table->item(row, column)->text();
        bool conversionOk = false;
        double data = dataTxt.toDouble(&conversionOk);
    
        if(conversionOk) {
           // some insignificant code
        }
        else {
            ui->table->setItem(row, column, new QTableWidgetItem("0.0"));
        }
    }
    

    This code controls correctly entering number into a cell. When i write something like "asdfhausidfh" into the cell, the code change it to "0.0".

    But the program crash, when i write some incorrect data to the cell. Problem is in this row:

    ui->table->setItem(row, column, new QTableWidgetItem("0.0"));
    

    but i don't know why...

    Where could the problem be?

    0_1501485704709_Untitled.png



    1. Please post your stack trace at the moment of the crash so we can identify the problem
    2. That's not how you handle numerics in QTableWidgetItem. Don't focus just on the constructors, converting it to string just does not make sense. use something like:
    double someNumber = 5.0;
    QTableWidgetItem* itemToAdd = new QTableWidgetItem();
    itemToAdd->setData(someNumber);
    ui->table->setItem(row, column,itemToAdd);
    


  • Thank you very much for your answer.

    Problem is solved. I change my code:

    void MainWindow::on_table_cellChanged(int row, int column)
    {
        QTableWidgetItem *dataItem = ui->table->item(row, column);
        bool conversionOk = false;
        double data = dataItem->text().toDouble(&conversionOk);
    
        if(conversionOk) {
           // some insignificant code
        }
        else {
           dataItem->setText("0.0000");
        }
    }
    


  • Or just ignore me, I guess that works too 😉



  • No, i don't ignore, i tried it, but setData method must have 2 arguments:

    void QTableWidgetItem::setData(int role, const QVariant & value)
    

    And i don't know, what is the second arg.

    I'm new in the QT.



  • Actually, my fault. It's the first argument you are missing. What you should put in there is explained here: http://doc.qt.io/qt-5/qt.html#ItemDataRole-enum

    The correct line above is itemToAdd->setData(Qt::EditRole,someNumber);



  • This work great, thank you :)


Log in to reply
 

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