我正在使用Python和PySide2 Qt绑定。
我的程序旨在从csv文件加载记录,将它们显示为表中的行,并在被询问时将每个记录上载到远程数据库。每次上传都需要花费几秒钟的时间,所以我想在上传时更改每行的背景颜色,然后根据成功或失败将其再次更改为红色或绿色。
我有一个TableModel
类,扩展了QAbstractTableModel
。该程序无需编辑值,只需从csv加载它们,因此它无需实现setData()
,而只需实现data()
。我将它通过扩展的QSortFilterProxyModel
传递到QTableView
中以进行排序。
class TableModel(QAbstractTableModel):
records = [] #Where the list of records is kept
def data(self, index, role=Qt.DisplayRole):
record = self.records[index.row()]
if role == Qt.DisplayRole:
#bunch of table data stuff
elif role == Qt.BackgroundColorRole:
#This gets called all the time
#but is never called during the uploading process
if record.uploading: return QColor.cyan
def upload(self):
for recordRow in range(len(self.records)):
record = self.records[recordRow]
start = self.createIndex(recordRow, 0)
end = self.createIndex(recordRow, 4)
record.uploading = True
#I've tried both explicitly specifying the desired role
#as well as omitting the argument
self.dataChanged.emit(start, end, [Qt.BackgroundColorRole])
record.upload() #Currently just waits for 1 second
record.uploading = False
self.dataChanged.emit(start, end, [Qt.BackgroundColorRole])
如您所见,我设置了一个上传标志,发出dataChanged
信号,上传(实际上只是等待一秒钟),再次关闭该标志,然后再次发出dataChanged
。我希望看到青色高光在每一行上停留一秒钟,在列表中向下移动,但是什么也没发生。
当我监视data()
方法时,在上载迭代期间它永远不会被BackgroundColorRole
调用。
我也将测试方法连接到dataChanged
信号上,并且它确实以正确的索引发出。
我需要做其他事情才能正确连接dataChanged
吗?我的模型和视图之间的QSortFilterProxyModel
是否引起问题?
答案 0 :(得分:1)
主线程中的任务不应延迟超过30毫秒,因为它会阻塞GUI,从而避免执行事件循环,因此信号不会通知,导致GUI的更新不会发生。因此,您应该在线程上运行它,或者最好使用QtNetwork,因为它与Qt事件循环友好。