Home > Net >  PyQt5: fill QTableWidget from sqlite3 database
PyQt5: fill QTableWidget from sqlite3 database

Time:07-29

I am coding a program being about the management of the products in a grocery. I use PyQt5 in order to make a GUI for my program, and I have a button which is responsible for listing all of the data in the database and a QTableWidget being responsible for holding the data. When I click that button, it needs to put the data in the database into the QTableWidget, but it gets nothing for me. I am not going to be able to post all part of my program, because code of my program is too long. I am going to only post the required part.

Here are is code:

def ListProducts(self):
    self.curs.execute("SELECT * FROM Products")
    self.conn.commit()
    self.ui2.ProductTable.clear()
    for lineIndex, lineData in enumerate(self.curs):
        for columnIndex, columnData in enumerate(lineData):
            self.ui2.ProductTable.setItem(lineIndex, columnIndex,QtWidgets.QTableWidgetItem(str(columnData)))

CodePudding user response:

By default, a QTableWidget has no size, so its row and column counts must be defined before setting new items. In your case, the counts are initially unknown, since they are determined by the sqlite select statement, but the table can be resized dynamically whilst adding the data:

def ListProducts(self):
    self.curs.execute("SELECT * FROM Products")
    self.ui2.ProductTable.clear()
    for lineIndex, lineData in enumerate(self.curs):
        if lineIndex == 0:
            # SET COLUMN COUNT
            self.ui2.ProductTable.setColumnCount(len(lineData))
        # ADD NEW ROW
        self.ui2.ProductTable.insertRow(lineIndex)
        for columnIndex, columnData in enumerate(lineData):
            # FILL ROW
            self.ui2.ProductTable.setItem(lineIndex, columnIndex, QtWidgets.QTableWidgetItem(str(columnData)))
  • Related