[PyQt] Signal on Selection in QTreeView

Marius Kintel kintel at sim.no
Tue Mar 18 12:41:11 GMT 2008


On Mar 18, 2008, at 2:57 AM, Kevin Foss wrote:

> 	To show you my difficulties, I've tried to test this whole  
> selection model
> capability using an example from David Boddie at Trolltech.  It can  
> be found
> here:
>
> http://www.opensubscriber.com/message/pyqt@riverbankcomputing.com/8447872.html
>
>      	Guess what, even his example doesn't work.  When I run his  
> example,
> nothing is printed when an item is selected.
>

I think I can help.
I spend a lot of time figuring out how this works a month or so back.
My results can be summed up like this:

    ** Never connect a Qt signal to a global python function **

    If the python wrapper object dies (common for temporary wrapper  
objects), the connection goes down with it. Instead, connect to a  
python instance method. This is handled in a special way in SIP making  
the connection survive the temporary python wrapper object.

Taking my own advice, the example program you mention can be fixed by  
making the slot an instance method instead:

import sys
from PyQt4.QtCore import QObject, SIGNAL
from PyQt4.QtGui import *

class MyClass:
     def slot(self, selected, deselected):
         print len(selected), "items selected"
         print len(deselected), "items deselected"


if __name__ == "__main__":

     app = QApplication(sys.argv)
     model = QStandardItemModel()
     for i in range(10):
         model.appendRow([QStandardItem("Item %i" % i)])

     listView = QListView()
     listView.setModel(model)
     listView.show()

     myobj = MyClass()
     QObject.connect(listView.selectionModel(),
         SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
         myobj.slot)

     sys.exit(app.exec_())

~/= Marius

--
We are Elektropeople for a better living.






More information about the PyQt mailing list