i faced problem in CRUD methods, i'm using pyqt5 and python 3.9, i want to display data from database and present it into a qtableview, i have tow problem the first one the method did no work ,and the second one is :i do not know how to automatically make the function work , i want the application to activate when i navigate to the interface to make every teacher see the student he have
this is my code
connection = mc.connect(host=cr.host, user=cr.user, password=cr.password, database=cr.database) cur = connection.cursor()
rows = "select count(*) from student"
query = "SELECT Student_id, FirstName, LastName FROM student"
cur.execute(query)
result = cur.fetchall()
print("heel")
while query.next():
print("heel")
rows = self.view.rowCount()
self.view.setRowCount(rows + 1)
self.view.setItem(rows, 0, self.Student_List(str(query.value(0))))
self.view.setItem(rows, 1, self.Student_List(query.value(1)))
self.view.setItem(rows, 2, self.Student_List(query.value(2)))
self.view.resizeColumnsToContents()
except mc.Error as e:
print(e)
this is the my table view
self.model = QSqlTableModel(self)
self.model.setTable("contacts")
self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
self.model.setHeaderData(0, Qt.Horizontal, "Student_id")
self.model.setHeaderData(1, Qt.Horizontal, "FirstName")
self.model.setHeaderData(2, Qt.Horizontal, "LastName")
self.model.select()
If you want to display the data automatically, do not use method because if you want you should call it. The code will be messy but it will work for you.
Months ago I had create a CRUD app using tablewidget, but if you want to display just the data, you should use tableview.
This code will work for you if you want use qtablewidget, but if you use tableview you should create model or use pyqt predefined classes
try:
connection = mc.connect(host=cr.host, user=cr.user, password=cr.password, database=cr.database)
cur = connection.cursor()
cur.execute("SELECT * FROM student")
result = cur.fetchall()
self.list.setRowCount(0)
print("ff")
for row_number, row_data in enumerate(result):
self.list.insertRow(row_number)
for column_number, data in enumerate(row_data):
self.list.setItem(row_number, zcolumn_number, QTableWidgetItem(str(data)))
except mc.Error as e:
print(e)
Note: list
is the name of the table