如何从 PySide 中的 .ui 文件加载子项? [英] How do I load children from .ui file in PySide?

查看:41
本文介绍了如何从 PySide 中的 .ui 文件加载子项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我是这样加载它们的:

For now I'm loading them like this:

if __name__ == '__main__':
    app = QApplication(sys.argv)
    loader = QUiLoader()
    file = QFile('main.ui')
    file.open(QFile.ReadOnly)
    window = loader.load(file)
    file.close()
    window.show()
    # Here:
    window.centralwidget.findChild(QListWidget, 'listWidget').addItems(['Item {0}'.format(x) for x in range(100)])
    sys.exit(app.exec_())

但我认为这很不舒服,有没有其他方法,可能是加载整个命名空间或其他什么?

But I think it's uncomfortably, is there any other way, probably to load whole namespace or whatever?

推荐答案

目前,PySide QUiLoader 类没有一种方便的方法将小部件加载到顶级类的实例中,例如 PyQt uic 模块有.

At the moment, the PySide QUiLoader class doesn't have a convenient way to load widgets into to an instance of the top-level class like the PyQt uic module has.

但是,添加等效的内容相当容易:

However, it's fairly easy to add something equivalent:

from PySide import QtGui, QtCore, QtUiTools

class UiLoader(QtUiTools.QUiLoader):
    _baseinstance = None

    def createWidget(self, classname, parent=None, name=''):
        if parent is None and self._baseinstance is not None:
            widget = self._baseinstance
        else:
            widget = super(UiLoader, self).createWidget(classname, parent, name)
            if self._baseinstance is not None:
                setattr(self._baseinstance, name, widget)
        return widget

    def loadUi(self, uifile, baseinstance=None):
        self._baseinstance = baseinstance
        widget = self.load(uifile)
        QtCore.QMetaObject.connectSlotsByName(widget)
        return widget

然后可以这样使用:

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(self, parent)
        UiLoader().loadUi('main.ui', self)
        self.listWidget.addItems(['Item {0}'.format(x) for x in range(100)])

为了使其正常工作,loadUibaseinstance 参数必须是 Qt Designer 文件中顶级类的实例.然后所有其他小部件将作为实例属性添加到其中.

For this to work properly, the baseinstance argument of loadUi has to be an instance of the top-level class from Qt Designer file. All the other widgets will then be added to it as instance attributes.

这篇关于如何从 PySide 中的 .ui 文件加载子项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆