Why in pyqt5 should I use pyuic5 and not uic.loadUi("my.ui")?

Question:

I’ve been experimenting with QT5 for Python, using pyqt5. I’ve noticed that most tutorials recommend using pyuic5 to convert the XML UI to Python code. I’ve also seen a couple of tutorials where instead they use uic.loadUi(“myui.ui”) to dynamical load the XML UI. This seems like a cleaner, more modular solution to me, but it appears to be an unpopular option. Is there a reason converting your code with pyuic5 is a sounder solution?

Asked By: Frank

||

Answers:

Both solutions are good, they have advantages and disadvantages that have to be weighed with what you want to do, and many times it will depend on the taste of the programmer.

pyuic5:

  • Allows inheritance [+]

  • There is no additional load when running the application [+]

  • Convert the .ui to .py every time the file is modified [-]

uic.loadUi():

  • You do not have to modify anything when modifying the .ui [+]

  • Compilation extra time [-]

  • Does not allow inheritance (You could implement the inheritance using uic.loadUiType()) [-]

  • Does not allow the use of inspect [-].

Answered By: eyllanesc

The biggest reason to use pyuic5 is that IDEs (e.g. Visual Studio Code, PyCharm) do not understand .ui files, and therefore cannot provide code introspection (e.g. autocompletion of widget names) for your class unless you compile it to Python.

Answered By: Jussi Nurminen

Having looked into this more, for me dynamically loading the form generated by QT Designer is the way to go. You can get round the problems of not having access to the underlying widgets with commands like this (assuming you have a label called bob_label in your form):

self.bob_label: QLabel = self.findChild(QtWidgets.QLabel, 'bob_label')

In PyCharm, at any rate, this will automatically enable Intellisense (so the IDE now knows that there’s a label in the window class called bob_label). In Visual Studio Code despite great effort I couldn’t find a way to get this to work easily, although I did manage it eventually.

Answered By: Andy Brown
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.