LoginSignup
4
0

More than 3 years have passed since last update.

PySide2 ファイルの更新を検知する

Last updated at Posted at 2020-12-12

この記事はTakumi Akashiro ひとり Advent Calendar 2020の12日目の記事です。

始めに

またQtネタです。今日はファイルの更新を検知します。

使うクラスはQFileSystemWatcher!分かりやすい名前ですね。
QFileSystemWatcher Class | Qt Core 5.15.2

QFileSystemWatcherインスタンスが保持しているパスのリストを監視し、変更や追加、削除があった場合にfileChangedシグナルとかに通知を飛ばします。

じっせーん

では使っていきましょう。

#!python3
# encoding:utf-8

from PySide2 import QtCore
from PySide2 import QtWidgets

class Window(QtWidgets.QListView):
    def __init__(self):
        super().__init__()
        self.model = StringListModel()

        self.setModel(self.model)

        self.watcher = QtCore.QFileSystemWatcher()
        self.watcher.addPath("d:/hoge.txt")
        self.watcher.fileChanged.connect(self.append_to_model)

    def append_to_model(self, path):
        self.model.append(f"changed {path} !")

class StringListModel(QtCore.QAbstractListModel ):
    def __init__(self):
        super().__init__()
        self.__data = []

    def rowCount(self, parent=QtCore.QModelIndex()):
        if parent.isValid():
            return 0
        return len(self.__data)


    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            return self.__data[index.row()]

    def append(self, text):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self.__data.append(text)
        self.endInsertRows()

if __name__ == "__main__":
    app = QtWidgets.QApplication()
    window = Window()
    window.show()

    exit(app.exec_())

12_01.gif

できましたね!

締め

これでExcelなどでゲームデータを管理していても、DCCツール側でファイル上書きを感知して、現在開いているシーンを更新できそうですね!
…まあ……やったことは無いんですが。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0