【问题标题】:resetItems PyQt - how to reload scriptresetItems PyQt - 如何重新加载脚本
【发布时间】:2017-07-29 21:03:29
【问题描述】:

这只是我脚本的一部分。当 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'

我应该改变什么来刷新数据?

【问题讨论】:

  • 除非您已全局定义它,否则 stockdata 变量在构造函数之外不存在,但您正尝试在 getItems 和 resetItems 函数中使用它。也许您的意思是 self.stockdata?
  • 是的,我的意思是 getItems 中的 self.stockdata 但它仍然不能解决问题。

标签: python linux pyqt


【解决方案1】:

您收到错误是因为您的QFileSystemWatcher emits a string 的fileChanged 信号正在由resetItems() 接收,它期待StockListModel 的实例。 self 引用未通过,因为 file_check 已被定义为静态且未绑定到特定实例。

尝试将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()
        ...

【讨论】:

  • 是的,只要像这样在构造函数中定义它。不需要作为参数传入
  • file_check = QtCore.QFileSystemWatcher(['/home/user/Desktop/plik.txt']) file_check 仅检查文件是否已更改,如果是: file_check.fileChanged.connect(resetItems) 它发送信号'resetItems' 和 'resetItems' 应该重新加载数据,对吗?
  • file_check 将在它正在监视的任何文件发生更改时触发 fileChanged 信号。字符串参数是发送是更改的文件的路径。您对此做什么取决于您要达到的目标。 resetItems 应该做什么?我怀疑您可能想要更改 self.stockdata = stockdata 行以重新加载刚刚更改的文件的内容并更新模型
  • 是的,我想更改单元格的内容(重新加载数据)。这就是我使用 resetItems 的原因,它因为 'string' 而不起作用
  • 答案在这篇文章下面:stackoverflow.com/questions/24410025/…
猜你喜欢
  • 2017-04-14
  • 1970-01-01
  • 2019-05-03
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
相关资源
最近更新 更多