32

I am looking for a simple example of how to directly load a QtDesigner generated .ui file into a Python application.

I simply would like to avoid using pyuic4.

denysonique
  • 15,277
  • 6
  • 35
  • 40

4 Answers4

50

For the complete noobs at PySide and .ui files, here is a complete example:

from PySide import QtCore, QtGui, QtUiTools


def loadUiWidget(uifilename, parent=None):
    loader = QtUiTools.QUiLoader()
    uifile = QtCore.QFile(uifilename)
    uifile.open(QtCore.QFile.ReadOnly)
    ui = loader.load(uifile, parent)
    uifile.close()
    return ui


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = loadUiWidget(":/forms/myform.ui")
    MainWindow.show()
    sys.exit(app.exec_())
BarryPye
  • 1,715
  • 2
  • 16
  • 19
39

PySide, unlike PyQt, has implemented the QUiLoader class to directly read in .ui files. From the linked documentation,

loader = QUiLoader()
file = QFile(":/forms/myform.ui")
file.open(QFile.ReadOnly)
myWidget = loader.load(file, self)
file.close()
qasfux
  • 207
  • 1
  • 8
Stephen Terry
  • 5,989
  • 1
  • 26
  • 31
  • 22
    Just to help noobs along: QUiLoader is from `PySide.QtUiTools.QUiLoader` – brews Mar 15 '13 at 18:07
  • 1
    All I get is this: `QPixmap: Must construct a QApplication before a QPaintDevice Aborted (core dumped)` – Lucio Jun 02 '13 at 03:08
  • 3
    @Lucio The code snippet in this answer cannot be used in isolation. Follow BarryPye's answer for a complete example. – JBentley May 05 '14 at 20:30
6

Another variant, based on a shorter load directive, found on https://askubuntu.com/questions/140740/should-i-use-pyqt-or-pyside-for-a-new-qt-project#comment248297_141641. (Basically, you can avoid all that file opening and closing.)

import sys
from PySide import QtUiTools
from PySide.QtGui import *

app = QApplication(sys.argv)
window = QtUiTools.QUiLoader().load("filename.ui")
window.show()
sys.exit(app.exec_())

Notes:

  • filename.ui should be in the same folder as your .py file.
  • You may want to use if __name__ == "__main__": as outlined in BarryPye's answer
Community
  • 1
  • 1
lofidevops
  • 13,448
  • 13
  • 75
  • 107
  • This one actually works with PySide2. Just add `from PySide2.QtWidgets import QApplication` – texnic Feb 23 '19 at 10:52
0

Here is some example for PySide6 and Windows. (For linux you need use /, not \\)

from PySide6.QtUiTools import QUiLoader
from PySide6.QtCore import QFile
from PySide6.QtWidgets import QApplication
import sys

if __name__ == "__main__":
    app = QApplication(sys.argv)
    loader = QUiLoader()
    file = QFile("gui.ui")
    file.open(QFile.ReadOnly)
    ui = loader.load(file)
    file.close()
    ui.show()
    sys.exit(app.exec_())
Marvin Noll
  • 515
  • 1
  • 5
  • 18
Emrexdy
  • 81
  • 1
  • 2
  • 7