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

Error by adding items in a QTableWidget using "for"



  • I don't know why but it's not adding any item, here is the code

    void BarramDialog::setshunts(QStringList tipo,QStringList nome)
    {
        QStringList titulos;
        titulos <<"Tipo"<<"Nome";
        ui->tabela_shunts->setColumnCount(2);
        ui->tabela_shunts->setHorizontalHeaderLabels(titulos);
    
        if(tipo.length()==0){
            return;
        }
        else {
        ui->tabela_shunts->setRowCount(tipo.length());
        ui->tabela_shunts->setItem(0,0,new QTableWidgetItem(nome[0]));
    
        for(int i=0;(i=(tipo.length()-1));i++){
    
            QString type=tipo[i];
            QString name=nome[i];
            ui->tabela_shunts->setItem(i,0,new QTableWidgetItem(type));
            ui->tabela_shunts->setItem(i,1,new QTableWidgetItem(name));
        }
    }
    

    the function receives 2 QStringLists and (should) creates new items in the QTableWidget
    (I JUST TESTED WITH ONE ITEM IN EACH LIST SO FAR)
    But it doesn't work! not even if do something like this:

    for(int i=0;(i=(tipo.length()-1));i++){
    
            QString type=tipo[i];
            QString name=nome[i];
            ui->tabela_shunts->setItem(0,0,new QTableWidgetItem("teste"));
            ui->tabela_shunts->setItem(0,1,new QTableWidgetItem(name));
        }
    

    it just appears the Qtable whit one row, but nothing written inside of the 2 cells
    The only way to this code work is if i set the item outside the"for", how can i fix it?


  • Lifetime Qt Champion

    Hi,

    You are using fixed values for both row and column in your for loop. For what you want, you have to update the row value on each iteration.

    Note that your loop condition is wrong.



  • hi
    how can i update it?
    and why my loop condition is wrong?the number i goes of 0 to the lenght of the list -1, so if my list is made of 5 items the number i goes until it reaches the index 4.Why is it wrong?


  • Lifetime Qt Champion

    Well, use a variable for the row and update it.

    Because the condition is what make the loop continue. What you want is "i < count".



  • ohhh yeah it worked
    thanks man!!


Log in to reply