Search code examples
pythonqtpyqtqlistwidgetqlistwidgetitem

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


In the screenshot below is a QListWidget randomly populated with many QListWIdgetItems, wordWrap enabled, and with a scrollBar on the right side (note the selected item).

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

By now, I achieve this by walking over the y-range of the QListWidget.viewport().geometry() with a pixel distance equivalent to the line height (here: 29 pixels), applying a itemAt(0,y) to the QListWidget 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:
            itlist.append(i)
            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


Solution

  • 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()