Search code examples
python-3.xqtablewidgetpyqt5qtablewidgetitem

PyQt5 QTableWidget showing only first line and column


I have a QTableWidget populated with a list of lists. Each inner list have eight elements and my table have a ninth control column calculated after the others are loaded. I can read and print to console the content of any cell of the table like print(self.tAccounts.item(52,3).text()), so I think there is no problem with the data, but the table shows only the cell's content for the first line and column in the table, leaving the others bank. I should be making a mistake in some place, but I can't see.

Using PyQt 5 and Python 3.

The constructor

class Table(QWidget):
    def __init__(self, parent=None):
        super(Table, self).__init__(parent)

        self.accounts = [] # The source is created in the constructor\
                           # and populate in other member function
        self.tAccounts = QTableWidget(0,9)
        self.tAccounts.setSortingEnabled(True)
        self.tAccounts.setHorizontalHeaderLabels(['1','2','3','4','5','6','7','8','9'])
        self.tAccounts.resizeColumnsToContents()
        self.tAccounts.verticalHeader().hide()

The member function:

def loadDay(self):
    for row, account in enumerate(self.accounts):
        self.tAccounts.insertRow(row)
        for col in range(8):
            self.tAccounts.setItem(row, col, QTableWidgetItem(str(accounts[col])))
            self.tAccounts.item(row,col).setTextAlignment(Qt.AlignRight)
        self.tAccounts.setItem(row, 8, QTableWidgetItem('')) # defined for further use

Solution

  • Finally I found it.

    The problem is in enabling the sorting in the constructor. Seems the default sorting is Z-A. Changing the sort to A-Z by clicking in the header of the empty table solves the bug but the best solution is to move the line self.tAccounts.setSortingEnabled(True) to the end of the loadDay function. Seems to be a clash between the ever changing row number because of enabled sorting and the updating algorithm of QTableWidget