Bruno Ap
Bruno Ap

Reputation: 71

PyQT - QlistWidget with infinite scroll

I have a QlistWidget and I need to implement on this an Infinite Scroll, something like this HTML example:

https://scrollmagic.io/examples/advanced/infinite_scrolling.html

Basically, when the user scrolls to the last item of the list, I need to load more items and dynamically append it in the QlistWidget.

Is it possible? I didn't find any example yet.

Upvotes: 2

Views: 1176

Answers (1)

Aaron
Aaron

Reputation: 11075

There are likely many ways to achieve this task, but the easiest I found is to watch for changes in the scroll bar, and detect if we're at the bottom before adding more items to the list widget.

import sys, random
from PyQt5.QtWidgets import QApplication, QListWidget

class infinite_scroll_area(QListWidget): #https://doc.qt.io/qt-5/qlistwidget.html
    def __init__(self):
        super().__init__() #call the parent constructor if you're overriding it.
        #connect our own function the valueChanged event
        self.verticalScrollBar().valueChanged.connect(self.valueChanged) 
        self.add_lines(15)
        self.show()
    
    def valueChanged(self, value): #https://doc.qt.io/qt-5/qabstractslider.html#valueChanged
        if value == self.verticalScrollBar().maximum(): #if we're at the end
            self.add_lines(5)
    
    def add_lines(self, n):
        for _ in range(n): #add random lines
            line_text = str(random.randint(0,100)) + ' some data'
            self.addItem(line_text)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = infinite_scroll_area()
    sys.exit(app.exec_())

You can directly grab scroll wheel events by overriding the wheelEvent method of QListWidget, then do the logic there which solves the potential problem of not starting out with enough list items for the scrollbar to appear. If it's not there, it can't change value, and the event can't fire. It introduces a new problem however as scrolling with the mouse wheel is not the only way to scroll the view (arrow keys, page up/down keys, etc). With the number of classes and subclasses in any gui library, it becomes imperative to get really familiar with the documentation. It's a little inconvenient that it isn't as comprehensive for python specifically, but I think the c++ docs are second to none as far as gui library documentation goes.

Upvotes: 2

Related Questions