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:
- A Counter Flag
- Row Count
- Column Count
- Data (Obviously)
To insert data into the table you could do something like this.
def add_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 tablewidget
for i in range(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:
def load_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]))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…