[PyQt] Signal on Selection in QTreeView

Matt Newell newellm at blur.com
Tue Mar 18 17:52:20 GMT 2008

On Tuesday 18 March 2008 09:46:06 fossks at cox.net wrote:
> Phil/Andreas,
>      I've been experimenting again using some of the recommendations and
> some examples I have found.   Please look at the new example I am working
> with, which is below.
>     I can now have a reaction to a selected item in a list.  When something
> is selected, the 'slot' function is called and is run.  Great!   In this
> case it prints out some details including the number of rows, etc.
>     Now I am still trying to access a reference to the selected item so I
> can pull the data from the original list and display it elsewhere in a
> different widget.  The original author of this modified program included a
> function call called "data".   However, I cannot figure out how to use it. 
> I guess my hangup is the index and role fields.  I don't know what to put
> in those fields to get the currently selected item.
>     In my case I need the current row, that is the current row number.  I
> don't need to fiddle around with the row entries as I already have them in
> the original list.
>    Could someone help me write a simple function called
> "get_current_row_number", which returns an integer indicating the
> highlighted row?
> Kevin

You just need to get the QModelIndexes from the QItemSelection 'selected' 
object in your slot, then call row() on them.

The QItemSelection is a list of QItemSelectionRange objects.  Each 
QItemSelectionRange contains 1 or more selected QModelIndexes, represented 
from a topleft to bottom right with the same parent.

>     def slot(self, selected, deselected):
	# this will give you an index for each row and col
	# so if you have multiple columns selected you will get duplicates
	for idx in selected.indexes():
		print idx.row()
	# Here is how to get the rows even if there are multiple columns selected
	# This ignores the indexes' parents, which is fine if your
	# model is 2 dimensional
	for selectionRange in selected:
		for i in 
			print "Row %i selected" % i


More information about the PyQt mailing list