Sophus
Sophus

Reputation: 491

PyQt: How do I load a ui file from a resource?

In general, I load all my ui files via the loadui() method, and this works fine for me. This looks like this:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

'''
The modules for Qt are imported.
PyQt are a set of Python bindings for Qt.
'''
from PyQt4.QtGui import QDialog
from PyQt4.uic import loadUi
from PyQt4.QtCore import Qt, QFile
from PyQt4 import QtCore

class My_Window(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)

        UI_PATH = QFile(":/ui_file/test.ui")

        UI_PATH.open(QFile.ReadOnly)

        self.ui_test = loadUi(UI_PATH, self)

        UI_PATH.close()

Now I try to load the ui file via loaduiType(), but it doesn't work. I tried with this code:

from PyQt4.uic import loadUiType

UI_PATH = QFile(":/ui_file/test.ui")

Ui_Class, _ = loadUiType(UI_PATH)

class Test_Window(QDialog, UiClass):
    def __init__(self, parent):
        QDialog.__init__(self, parent)

        self.setupUi(self)

What is the correct and best why to load the ui file with the loadUiType() method?

Upvotes: 2

Views: 3913

Answers (1)

ekhumoro
ekhumoro

Reputation: 120618

It's not really much different from what you were already doing:

from PyQt4.QtCore import QFile
from PyQt4.uic import loadUiType

import resources_rc

def loadUiClass(path):
    stream = QFile(path)
    stream.open(QFile.ReadOnly)
    try:
        return loadUiType(stream)[0]
    finally:
        stream.close()

Ui_Class = loadUiClass(':/ui_file/test.ui')

Upvotes: 3

Related Questions