我有一个QScrollArea
,里面有很多小部件。
我无法找到一种方法来检测滚动后哪些小部件可见。
滚动后有没有办法检测哪些小部件在哪里?
答案 0 :(得分:1)
如果您想知道哪个小部件可见,请使用此功能:
def isVisibleWidget(widget):
if not widget.visibleRegion().isEmpty():
return True
return False
如果您只想检测移动滚动,则必须使用以下信号生成的信号:
{your QScrollArea}.verticalScrollBar()
{your QScrollArea}.horizontalScrollBar()
在示例中使用valueChanged
信号
示例:强>
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_())
输出:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']
输出:
['6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19']