[PyQt] is there any reason why the former does not work?

Brian Kelley kelley at eyesopen.com
Sun Oct 11 23:46:56 BST 2009


First, because models can be shared between views, you have to retain  
hold of the model yourself, in previous versions of PyQt

> view.setModel(QStandardItemModel())

would probably crash because QStandardItemModel() goes out of scope  
and gets referenced counted because QTableView does not grab hold of a  
reference to it.

It looks like Phil has added a smart-ish pointer that does the "right  
thing" in these cases to prevent crashing but maintain the original Qt  
behavior but can be confusing in the python world.

One of the neatish features  of python is the following:

view = QTableView()
view.mymodel = QStandardItemModel()
view.setModel(view.mymodel)

This works because of the dynamic nature of python but is kind of an  
ugly hack, it is best to subclass:

class MyView(QTableView):
    def __init__(self):
            QTableView.__init__(self)

   def setModel(self, model):
          self.mymodel = model
          QTableView.setModel(self, model)

Brian

On Oct 11, 2009, at 6:36 PM, Victor Noagbodji wrote:

> hello list,
>
> i have tried in vain to get my head around this problem. (for the lack
> of time please accept this rudimentary code)
>
> view = QTableView()
> view.setModel(QStandardItemModel())
>
> print view.model() <---- returns None
>
> but
>
> view = QTableView()
> model = QStandardItemModel()
> view.setModel(model)
>
> print view.model() <---- correctly prints
> <PyQt4.QtGui.QStandardItemModel object at ...>
>
> why is that happening?
>
> -- 
> paul victor noagbodji
> _______________________________________________
> PyQt mailing list    PyQt at riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt




More information about the PyQt mailing list