How do I load children from a .ui file into PySide?
Now I load 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 this is awkward, is there any other way, maybe load the full namespace or something?
+3
source to share
1 answer
Currently, the PySide QUiLoader class does not have a convenient way to load widgets into a top-level class instance like the PyQt uic module .
However, it's pretty 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
Which then could be used like this:
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)])
The argument baseinstance
loadUi
must be an instance of the top-level class from Qt's constructor file to work properly . Then all other widgets will be added to it as instance attributes.
+4
source to share