Search code examples
pythonpyqt5

Get data from qtablewidget in 2d array


I have Qtablewidget and a PushButton. When a button pressed I want that data(flot number) in Qtablewidget exctracted/trandformed(dont know how to describe it) in 2d array and then pass to previously made function.

I created a cycle:

    def DoSomething(self):
        for i in range(self.ui.Level_N.rowCount()):
            for j in range(self.ui.Level_N.columnCount()):
                T=self.ui.Level_N.item(i,j).text()
        print (T)

But it prints only last element of table. I know that I should somehow print that T is 2d array, but I dont know how.


Solution

  • You should create the "top level" list outside of the main loop, and each "row" outside of the inner one.

    Note that you should always check that item() is valid before calling its methods, because unless the item value was edited by the user (or set in Designer) or explicitly set with setItem(), it will return None and you'll get an AttributeError.

    You should also decide how to deal with non existing items or items that don't contain numeric values. In the following example, I used 0 as a fallback value.

    def doSomething(self):
        array = []
        for i in range(self.ui.Level_N.rowCount()):
            row = []
            array.append(row)
            for j in range(self.ui.Level_N.columnCount()):
                item = self.ui.Level_N.item(i,j)
                if item:
                    try:
                        row.append(float(item.text()))
                    except TypeError:
                        row.append(0)
                else:
                    row.append(0)
        print(array)