Jochen Schwarze Jochen Schwarze - 9 months ago 90
Python Question

PyQt derive y pixel coordinates of QListWidgetItems currently visible in a QListWidget

In the screenshot below is a

randomly populated with many
enabled, and with a
on the right side (note the selected item).

What I'm after are the y positions of each (visible)
relative to the

By now, I achieve this by walking over the y-range of the
with a pixel distance equivalent to the line height (here: 29 pixels), applying a
to the
and append the fount items to a list, if they are not allready in it.

code is like:

def reportItems(self):
l = self.listWidget
dy = l.item(0).font().pointSize()
ystart = l.viewport().geometry().y()
h = l.viewport().geometry().height()
print ystart, h, dy
itlist = []
itcomplist = []
for y in range(ystart, ystart+h, (29/8)*dy): #empirical value
i = l.itemAt(0, y)
if not i in itlist:
itcomplist.append((y, l.row(i)))
for it in itcomplist:
y, i = it
print y, l.item(i).text()[:30]

This way seems not very elegant to me since it is slow and performs redundant queries.

Is there a smarter way to find all the y coordinates?

enter image description here

Answer Source

You can get a list of the model indexes, then loop over them and call QListWidget.visualRect to get the location of the item/index in local viewport coordinates

for row in range(listwidget.count()):
    index = listwidget.model().index(row)
    rect = listwidget.visualRect(index)
    print rect.y()