[PyQt] treeview

David Boddie david at boddie.org.uk
Fri Oct 19 00:19:04 BST 2007


On Tue Oct 16 16:41:26 BST 2007, lucaberto wrote:

> Hello can you explain me why if i do this :
> 
> import sys
> from PyQt4 import QtCore, QtGui
> 
> if __name__ == "__main__":
>     app = QtGui.QApplication(sys.argv)
>     
>     model = QtGui.QDirModel()
>     tree = QtGui.QTreeView()
>     tree.setModel(model)
>     
>     tree.setWindowTitle(tree.tr("Dir View"))
>     tree.resize(640, 480)
>     tree.show()
>     
>     sys.exit(app.exec_())
> 
> All works

This works because you have created both a model and a tree view, and you
have connected them together with the view's setModel() method.

> But if i do this:
> 
> import sys
> from PyQt4 import *
> from PyQt4 import  QtGui
> from form_rinomina_file_impl import Form
> app = QtGui.QApplication(sys.argv)
> form = Form()
> form.show()
> app.exec_()

OK, so no model here, but...

> class Form(QWidget, Ui_Form):

[...]

>     def faccio_lista(self):
>         modello = QtGui.QDirModel()
>         self.treeView.setModel(modello)

Here, you create a model and set it on the view, but it immediately goes
out of scope and is deleted, so the view has no model to show.

Views don't take ownership of models because no single view should own
them. This means that you have to do one of two things:

 1. Create the model with a parent; for example:

    modello = QtGui.QDirModel(self)

 2. Store the model in the instance of your Form class:

    self.modello = QtGui.QDirModel()
    self.treeView.setModel(self.modello)

Hope this helps,

David



More information about the PyQt mailing list