LoginSignup
11
8

More than 5 years have passed since last update.

PySideでuiファイルが更新されたらpyファイルに自動変換する

Last updated at Posted at 2016-12-24

QtDesignerを使って.uiファイルを作成していると、ファイルを更新するごとにpyside-uicでpyファイルに変換する必要があり、非常に面倒だ。

uiファイルが更新されたら、自動でpyside-uicで変換するスクリプトを書く。

watchdogモジュールを使う

ファイルの更新監視はwatchdogモジュールを使う、非常に便利なモジュールである。
インストールはpipで簡単に行える。

pip install watchdog

次にuiファイルが存在するルートディレクトリにwatchdog_uic.pyというファイルを作る。

#! usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
import os
import time
import subprocess
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

BASE_DIR = os.path.abspath(os.path.dirname(__file__))


class UicHandler(PatternMatchingEventHandler):
    def on_modified(self, event):
        ui_file = event.src_path
        output_file = os.path.splitext(ui_file)[0] + "_ui.py"
        cmd = " ".join([
            "pyside-uic",
            "-o " + output_file,
            ui_file
        ])
        print(cmd)
        subprocess.call(cmd, shell=True)


def main():
    while True:
        event_handler = UicHandler(["*.ui"])
        observer = Observer()
        observer.schedule(event_handler, BASE_DIR, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()


if __name__ == "__main__":
    main()

上の例では.uiファイルを_ui.pyという命名規則に変更している。
命名規則のルールは各自実装してほしい。

python watchdog_uic.py

このスクリプトを起動しておくと、スクリプトファイル以下のディレクトリにuiファイルをすべて監視&コンバートしてくれる。

半年ほど前からwatchdogで自動変換いるが、楽すぎてもう手動コンバートに戻れない。

追記 2017-01-06

「最強のPySide/PyQt開発環境もPyCharmである」でPyCharm上で、自動変換する方法を書いた。
そちらも併せて参照されたい。

11
8
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
11
8