简体   繁体   中英

How do I detect if a widget is in sight? PyQt

I have a QScrollArea with lot of widgets in it.

I couldn't find a way to detect which widgets is in sight after scroll.
Is there a way to detect which widgets is in sight after scroll?

If you want to know which widget is visible use this function:

def isVisibleWidget(widget):
    if not widget.visibleRegion().isEmpty():
        return True
    return False

If you only want to detect the moving the Scroll you must use the signals generated by:

{your QScrollArea}.verticalScrollBar()
{your QScrollArea}.horizontalScrollBar()

In the example use the valueChanged signal

Example:

import sys

from PyQt5.QtWidgets import QApplication, QPushButton, QScrollArea, QVBoxLayout, QWidget


class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)

        widget = QWidget()
        layout = QVBoxLayout(self)
        self.buttons = []
        for i in range(20):
            btn = QPushButton(str(i))
            self.buttons.append(btn)
            layout.addWidget(btn)
        widget.setLayout(layout)
        scroll = QScrollArea()
        scroll.setWidget(widget)

        vLayout = QVBoxLayout(self)
        vLayout.addWidget(scroll)
        self.setLayout(vLayout)

        scroll.verticalScrollBar().valueChanged.connect(self.slot)
        scroll.horizontalScrollBar().valueChanged.connect(self.slot)
        self.show()
        self.slot()

    def slot(self):
        visibles = []
        for btn in self.buttons:
            if self.isVisibleWidget(btn):
                visibles.append(btn.text())
        print(visibles)

    def isVisibleWidget(self, widget):
        if not widget.visibleRegion().isEmpty():
            return True
        return False


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    sys.exit(app.exec_())

在此处输入图片说明

Output:

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']

在此处输入图片说明

Output:

['6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM