1
votes

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.

1
Usually on Stack Overflow, people include in their questions what they have already tried and where they got stuck. The Qt5 documentation is actually quite comprehensive, and pyqt5 is a nearly 100% direct translation of the native c++.Aaron
Just because I didn't post any code here, doesn't mean that I haven't tried yet. I am really stuck..otherwise I didn't need ask for help here.Bruno Ap
I am looking for some scroll event, on qlistwidget class, but I. found just a method, that can't trigger on user scroll, it works only when the user click.. Obs: I didn't ask for any code, I just need a conceptual help, to search for the right approach.Bruno Ap

1 Answers

1
votes

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.