How to load .ui file and use relative path when developing Addon,

Now I copy PyQt5.uic into addon directory’s Lib and then import it

from .Lib.PyQt5 import uic

uic.loadUi('C:/Users/Xavier/AppData/Roaming/Anki2/addons21/draft/ui/main.ui', self.mainWindow)
  1. I have tried uic.loadUi('.ui/main.ui', self.mainWindow), uic.loadUi('./ui/main.ui', self.mainWindow), uic.loadUi('ui/main.ui', self.mainWindow), but they all failed.

Is there any way to use relative path rathen than absolute path?

  1. For loading .ui file, I use uic, and so need PyQ5-tools, which is provided by Anki itself, so I need copy PyQt5 to project-root-dir/Lib, and then import using .Lib.PyQt5.

is there a module provided by Anki itself which can make me use it to load .ui file without install a module into my project directory’s Lib folder?

Thanks a lot.

Seems Anki doesn’t bundle the uic module. Try something like this:

import os
from PyQt5.QtWidgets import QDialog, QAction
from .Lib.PyQt5.uic import loadUi

from aqt import mw

def show_dialog():
    dialog = QDialog(mw)
    loadUi(os.path.join(os.path.dirname(__file__), "dialog.ui"), dialog)

action = QAction("my add-on")

1 Like

I recommend you use pyuic to compile it to a Python file instead. That way your editor will be able to autocomplete the UI elements, and there’s no extra overhead from parsing the ui files at runtime.

1 Like