[PyQt] Dumb question about QDirModel / setModel

Phil Thompson phil at riverbankcomputing.co.uk
Mon Sep 17 17:06:18 BST 2007


On Monday 17 September 2007, Nicolas Girard wrote:
> Hi,
> could someone tell me why this works...:
>
> #!/usr/bin/python
> from PyQt4 import QtGui
> import sys
>
> class Window(QtGui.QMainWindow):
>     def __init__(self, parent=None):
>         QtGui.QWidget.__init__(self, parent)
>         self.tree = QtGui.QTreeView(self)
>     def setModel(self,model):
>         tree=self.tree
>         tree.setModel(model)
>         tree.resize(640, 480)
>
> if __name__=="__main__":
>     app=QtGui.QApplication(sys.argv)
>     window=Window()
>     model = QtGui.QDirModel()
>     window.setModel(model)
>     window.show()
>     sys.exit(app.exec_())
>
> ... whereas this doesn't...?
>
> #!/usr/bin/python
> from PyQt4 import QtGui
> import sys
>
> class Window(QtGui.QMainWindow):
>     def __init__(self, parent=None):
>         QtGui.QWidget.__init__(self, parent)
>         self.tree = QtGui.QTreeView(self)
>         model = QtGui.QDirModel()
>         self.setModel(model)
>     def setModel(self,model):
>         tree=self.tree
>         tree.setModel(model)
>         tree.resize(640, 480)
>
> if __name__=="__main__":
>     app=QtGui.QApplication(sys.argv)
>     window=Window()
>     window.show()
>     sys.exit(app.exec_())

Views don't take ownership of the model (because models are sharable) so you 
need to give them a parent or keep an explicit reference (as you are doing in 
the first example but not in the second).

Phil


More information about the PyQt mailing list