MindRoller
MindRoller

Reputation: 241

C++ Qt - Setting QTableWidget items values

I've been working on a Matrix Calculator in Qt and encountered following problem. I do this:

void ShowMatrix::updateTable()
{
    int w = 323 - 305;
    int h = 300 - 227 + 15;

    for(int i = 0; i < matrix->getRows(); i++)
    {
        ui->tableWidget->insertRow(i);
        h += 35;
    }
    for(int j = 0; j < matrix->getColumns(); j++)
    {
        ui->tableWidget->insertColumn(j);
        w += 50;
    }

    this->resize(w, h);
    this->setMinimumSize(w, h);

    ui->retranslateUi(this);


    this->setWindowTitle(matrix->getName());
    emit updatingDone();

}

And after that, when updatingDone(); signal is emitted, this slot is launched:

void ShowMatrix::setValues()
{
    QString str;
    for(int i = 0; i < matrix->getRows(); i++)
        for(int j = 0; j < matrix->getColumns(); j++)
        {
            ui->tableWidget->item(i, j)->setText("1");
        }
    ui->retranslateUi(this);
}

I just want to set all the cells values to ones. I can not do anything with items, everything I am trying to do with them like setting flags, values etc. crashes my application. if I don't emit updatingDone() signal, everything works fine.

Upvotes: 0

Views: 8811

Answers (1)

Apin
Apin

Reputation: 2668

You can try to use this slot :

void ShowMatrix::setValues()
{
    QString str;
    for(int i = 0; i < matrix->getRows(); i++)
        for(int j = 0; j < matrix->getColumns(); j++)
        {
            QTableWidgetItem *item = ui->tableWidget->item(i, j);
            if(!item) {
                item = new QTableWidgetItem();
                ui->tableWidget->setItem(i, j, item);
            }
            item->setText("1");
        }
    ui->retranslateUi(this);
}

So when you add new row and/or column to table widget, those added cell(s) are still null. So you need to put QTableWidgetItem in those cells first using QTableWidget->setItem.

Upvotes: 2

Related Questions