0

Is it possible to find out the position relative to the QScrollbarArea and then jump to the item? In the example code, 50 labels are generated, as soon as I press the "Test" button I want to jump to a specific label.

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import *
import sys
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.scroll = QScrollArea()
        self.widget = QWidget()
        self.vbox = QVBoxLayout()

        for i in range(0,50):
            lbl = QLabel("TextLabel_"+str(i))
            self.vbox.addWidget(lbl)
        btn = QPushButton("Test")
        btn.clicked.connect(self.jumpToItem)
        self.vbox.addWidget(btn)
        self.widget.setLayout(self.vbox)

        #Scroll Area Properties
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.widget)

        self.setCentralWidget(self.scroll)

        self.setGeometry(0, 0, 100, 200)
        self.show()
    def jumpToItem(self, value):
        print("Jump to TextLabel_12")

def main():
    app = QApplication(sys.argv)
    main = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
Robin
  • 21
  • 3
  • 1
    Use [`ensureWidgetVisible()`](https://doc.qt.io/qt-5/qscrollarea.html#ensureWidgetVisible): `label = self.findChildren(QLabel)[12]` `self.scroll.ensureWidgetVisible(label, 0, 0)` – musicamante Mar 25 '23 at 19:14
  • Is it also possible that the widget is always displayed at the bottom? If I specify the "ymargin = 200" then you always end up in the middle instead of at the bottom... – Robin Mar 26 '23 at 19:53
  • Yes, it is, but that's a different question and requires further implementation. I suggest you to [edit] this question (I believe I've enough reputation to reopen it, otherwise you'll have to wait for 3 full reopen votes), or create a new question specifically related to that request. – musicamante Mar 26 '23 at 21:07

0 Answers0