Skip to content Skip to sidebar Skip to footer

Sqlite3 Table Into Qtablewidget, Sqlite3, Pyqt5

I have created a program that manages tables in a database, now i'm trying to make a gui for it, and i figured the easiest way would be to do it with Qt Designer and then convert i

Solution 1:

Before I answer this question, I highly recommend you open up your UI file in the Qt Designer and change your object names from tableWidget_2 and pushButton to something more appropriate as you are going to drive yourself insane.

Second of all, PyQt provides an entire API to work with databases called QtSql. You can access the api like so:

from PyQt5.QtSql import (QSqlDatabase, QSqlQuery) #and so on.

Rant over. I will answer your question now.

QTableWidgets are quite precarious to work with and require a couple of things:

  1. A Counter Flag
  2. Row Count
  3. Column Count
  4. Data (Obviously)

To insert data into the table you could do something like this.

defadd_values(self):
    self.count = self.count + 1# this is incrementing counter
    self.tableWidget_2.insertRow(self.count)
    self.tableWidget_2.setRowCount(self.count)
    # these are the items in the database
    item = [column1, column2, column3]
    # here we are adding 3 columns from the db table to the tablewidgetfor i inrange(3):
        self.tableWidget_2.setItem(self.count - 1, i, QTableWidgetItem(item[i]))

However, if you just want to load the data into the QTableWidget you could do something like this and call it in the setup:

defload_initial_data(self):
    # where c is the cursor
    self.c.execute('''SELECT * FROM table ''')
    rows = self.c.fetchall()

    for row in rows:
        inx = rows.index(row)
        self.tableWidget_2.insertRow(inx)
        # add more if there is more columns in the database.
        self.tableWidget_2.setItem(inx, 0, QTableWidgetItem(row[1]))
        self.tableWidget_2.setItem(inx, 1, QTableWidgetItem(row[2]))
        self.tableWidget_2.setItem(inx, 2, QTableWidgetItem(row[3]))

enter image description here

Post a Comment for "Sqlite3 Table Into Qtablewidget, Sqlite3, Pyqt5"