[英]How do I get the information that the user has changed in a table in PyQT with Python and SQLite3
我的GUI上有一个表格。 用户可以从GUI编辑该表。 如何获取已编辑的所有信息并在数据库中更新? 用户检查他们想要更新到数据库的每一行的复选框,因此我有一个需要更新的所有行的列表。 我想要一个元组列表,其中每个元组是一行需要更新的新值,因为ID字段保持不变(我也想知道如何让用户无法编辑某些字段)。
def click_btn_mailouts(self):
self.screen_name = "mailouts"
self.cur.execute("""SELECT s.StudentID, s.FullName, m.PreviouslyMailed, m.nextMail, m.learnersDate, m.RestrictedDate, m.DefensiveDate FROM
StudentProfile s LEFT JOIN Mailouts m ON s.studentID=m.studentID""")
self.all_data = self.cur.fetchall()
self.table.setRowCount(len(self.all_data))
self.tableFields = ["Check","Full name","Previously mailed?","Next mail","learnersDate","Restricted date","Defensive driving date"]
self.table.setColumnCount(len(self.tableFields))
self.table.setHorizontalHeaderLabels(self.tableFields)
self.checkbox_list = []
for i, item in enumerate(self.all_data):
FullName = QtGui.QTableWidgetItem(str(item[1]))
PreviouslyMailed = QtGui.QTableWidgetItem(str(item[2]))
LearnersDate = QtGui.QTableWidgetItem(str(item[3]))
RestrictedDate = QtGui.QTableWidgetItem(str(item[4]))
DefensiveDate = QtGui.QTableWidgetItem(str(item[5]))
NextMail = QtGui.QTableWidgetItem(str(item[6]))
self.table.setItem(i, 1, FullName)
self.table.setItem(i, 2, PreviouslyMailed)
self.table.setItem(i, 3, LearnersDate)
self.table.setItem(i, 4, RestrictedDate)
self.table.setItem(i, 5, DefensiveDate)
self.table.setItem(i, 6, NextMail)
chkBoxItem = QtGui.QTableWidgetItem()
chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
self.checkbox_list.append(chkBoxItem)
self.table.setItem(i, 0, self.checkbox_list[i])
"""here is the format that I have for the edit function"""
def click_btn_edit(self):
checkedRows = []
for i, checkbox in enumerate(self.checkbox_list):
if checkbox.checkState() == QtCore.Qt.Checked:
checkedRows.append(i)
"""as the list itterates, if the checkbox item is ticked,
it passes through the if statement, otherwise it is ignored.
checkedRows becomes a list of all the indexes in the table where
an edit needs to be made"""
所以基本上我需要知道如何在GUI中的QTableWidget中进行更改,给出已经进行了更改的索引列表,并以某种方式将这些更改更新到数据库中。 知道如何阻止用户编辑某些字段也会有所帮助,因为这会弄乱数据库。
你可以做一些不同的事情。
要阻止编辑,您只需删除不希望用户编辑的项目的编辑标志
FullName.setFlags(FullName.flags() & ~Qt.ItemIsEditable)
看起来你正在存储原始数据(即self.all_data
)。 您可以只将所选表格单元格中的数据与原始数据进行比较,并仅更新已更改的字段。
您还可以连接到表窗口小部件的itemChanged
信号,并保留自上次刷新以来已更改的所有索引的运行列表
...
self.changed_items = set()
self.table.itemChanged.connect(self.log_change)
def log_change(self, item):
self.changed_items.add(item)
或者,根据您想要的控制程度,您还可以创建一个QItemDelegate
来完成所有这些操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.