0

User sets values manually in all cells in a QTableWidget. The values of the first row of the table represent the values we want to store in a dictionary FirstRowDict. Second row values will be put in SecondRowDict and so on.

enter image description here

So from a table like one shown in the picture, we want to end up in this example with FirstRowDict={0:10,1:20} and SecondRowDict={0:30,1:40}

To achieve this i created a button and added an action that updates the target dictionaries when clicked:

def button_click():
    for j in range(0,2):
        FirstRowDict.update({i: float(str(tablewidget.itemAt(0,j).text()))})

        #I put "0" in itemAt because first row is zero
        #tablewidget = QTableWidget() declared earlier in the source code

        SecondRowDict.update({i: float(str(tablewidget.itemAt(1,j).text()))})

    print '1st_Row_Dict=%s'%1st_Row_Dict,'\n2nd_Row_Dict=%s'%2nd_Row_Dict

The output is not correct since the dictionaries are populated with same value and not the unique value of each cell. I get FirstRowDict={0:10,1:10} and SecondRowDict={0:10,1:10}

It seems that i have to create a new item using QTableWidgetItem http://doc.qt.nokia.com/4.7-snapshot/qtablewidget.html#item

Python begginer, some advice would be appreciated.

Ben
  • 51,770
  • 36
  • 127
  • 149
CosmoSurreal
  • 259
  • 6
  • 16
  • What do you get as output? BTW, `1st_Row_Dict` is not a valid name in Python. – Avaris Sep 16 '12 at 21:28
  • This is what i get:FirstRowDict={0:10,1:10}, SecondRowDict={0:10,1:10} .I edited the dictionary names because i just picked these names for the example – CosmoSurreal Sep 16 '12 at 21:32

1 Answers1

1

Ah, I see the confusion. itemAt returns the item at the given position, but it's not row/column. It's the coordinate (think of it as pixel).

Yes, you should use item instead of itemAt.

You don't need a str if you're going to convert it to float. float() will work on a QString as if it was a str. And, instead of .update, you can just assign the new value to the key.

FirstRowDict[i] = float(tablewidget.item(0, j).text())
Avaris
  • 35,883
  • 7
  • 81
  • 72