[PyQt] pyuic4 vs uic Module

Kyle Altendorf sda at fstab.net
Thu Aug 2 21:40:43 BST 2018

On 2018-08-02 16:01, Kyle Altendorf wrote:
> I was just chatting in #pyqt with someone about the same topic.  They
> were compiling right before import using uic.compileUi() so as to have
> actual .py files for the sake of IDE completion features.  I mentioned
> having considered making a Python import hook to catch and handle
> things like `import mywindow_ui` and do a build of `mywindow.ui` to
> `mywindow_ui.py` behind the scenes.  Not sure that 'magic' would
> really be worthwhile, but maybe I'll do it for fun at some point.

I'm not really sure it's a good thing but since I mentioned it, here's a 
first pass at an import hook.


import pathlib
import sys

import PyQt5.uic

class UiFinder:
     def find_spec(self, fullname, path, target=None):
         suffix = '_ui'

         if target is not None or not fullname.endswith(suffix):

         _, _, base = fullname.rpartition('.')
         base = base[:-len(suffix)]

         path, = path
         path = pathlib.Path(path)
         py_path = path / (base + suffix + '.py')
         ui_path = path / (base + '.ui')

         with open(py_path, 'w') as py:
             PyQt5.uic.compileUi(ui_path, py, indent=4)

def install_ui_finder():
     sys.meta_path.insert(0, UiFinder())


More information about the PyQt mailing list