Search code examples
pythonnonetype

'NoneType' object has no attribute 'text' in TableWidgets


I was trying to work with TableWidgets on Python and I ran into an issue.

I wanted to check whether the table is filled or not (with str of course).

def add_table (self):
    self.kala = self.comboBox.currentText()
    self.code_kala = self.comboBox.currentIndex()
    self.vahed = self.comboBox_2.currentText()
    list_e = []
    for i in list(range(10)):
        #self.tab = self.tableWidget.item(i,0)
        if self.tableWidget.item(i,0).text() != '':
        #if self.tab.text() !='':
            list_e.append(i)
        else:
            pass
    self.ROW = len(list_e)
    self.tableWidget.setItem(self.ROW,0,QTableWidgetItem(self.kala))
    self.tableWidget.setItem(self.ROW,1,QTableWidgetItem(str(self.code_kala)))
    self.tableWidget.setItem(self.ROW,2,QTableWidgetItem(str(self.vahed)))

and I don't know why I keep getting this error:

NoneType' object has no attribute 'text'

Does anyone know how to solve it?

Also, I know this code doesn't have any problem (I got good results with the same code in another project) but as cmd said:

File "D:\**\***\*****\*******\*\*************.py", line 1755, in add_table
    if self.tableWidget.item(i,0).text() != '':
AttributeError: 'NoneType' object has no attribute 'text'

Solution

  • It seems that the table widget might contain 'None' values, so you have to expect them to pop up. Instead of doing this:

        if self.tableWidget.item(i,0).text() != '':
    

    do that:

        thing = self.tableWidget.item(i,0)
        if thing is not None and thing.text() != '':
            # do stuff with thing