这只是我脚本的一部分。当 file.txt 中的数据更改时,我无法重新加载我的脚本(不停止它)。
class StockListModel(QtCore.QAbstractListModel):
def __init__(self, stockdata = [], parent = None):
QtCore.QAbstractListModel.__init__(self, parent)
self.stockdata = stockdata
self.file_check = QtCore.QFileSystemWatcher(['/home/user/Desktop/file.txt'])
self.file_check.fileChanged.connect(self.resetItems)
def getItems(self):
return stockdata
@QtCore.pyqtSlot(str)
def resetItems(self, path):
self.beginResetModel()
self.stockdata = self.stockdata #without this and next line I have the same
self.endResetModel() #error
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
app.setStyle("plastique")
tableView = QtGui.QTableView()
tableView.show()
a = os.popen("cat /home/user/Desktop/file.txt")
a = a.read()
time_variable = QtCore.QString("%s"%a)
model = StockListModel([time_variable])
tableView.setModel(model)
sys.exit(app.exec_())
当我运行此脚本并更新文件时,出现错误: AttributeError: 'QString' 对象没有属性 'beginResetModel'
我应该更改什么来刷新数据?
最佳答案
您收到错误是因为 QFileSystemWatcher
的 fileChanged
信号 emits a string ,它由 resetItems()
接收,它需要 StockListModel
的实例。 self
引用未通过,因为 file_check
已定义为静态且未绑定(bind)到特定实例。
尝试将 file_check
作为实例变量移动到构造函数中,并修改 resetItems()
以接受 fileChanged
发出的字符串参数。
编辑:为清晰起见添加了代码
构造函数:
def __init__(self, stockdata = [], parent = None):
QtCore.QAbstractListModel.__init__(self, parent)
self.stockdata = stockdata
self.file_check = QtCore.QFileSystemWatcher(['/home/user/Desktop/file.txt'])
self.file_check.fileChanged.connect(self.resetItems)
重置项目:
@QtCore.pyqtSlot(str)
def resetItems(self, path):
self.beginResetModel()
...
关于python - resetItems PyQt - 如何重新加载脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24383330/