PyQt:如何从资源加载ui文件?

时间:2016-10-03 13:16:37

标签: python qt pyqt pyqt4

一般情况下,我通过loadui()方法加载我的所有ui文件,这对我来说很好。这看起来像这样:

#!/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()

现在我尝试通过loaduiType()加载ui文件,但它不起作用。我试过这段代码:

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)

使用loadUiType()方法加载ui文件的正确和最佳原因是什么?

1 个答案:

答案 0 :(得分:2)

与你现在所做的并没有太大的不同:

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')