Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to keep horizontalScrollBar at the rightmost side?



  • I have a QScrollArea, and every time I push a button, a new QLabel will be added into it.
    4cfc616a-af63-4ed0-a1ed-470a8fb29dfa-image.png
    I tried these codes to keep the horizontalScrollBar at the rightmost side, but there's still some sapce left and thus the newest added QLabel can not show completely.

        def button_back(self):
            self.marquees_layout.addWidget(self.marquee_label())
            aa = self.main_ui.scrollArea.horizontalScrollBar().maximum()
            self.main_ui.scrollArea.horizontalScrollBar().setValue(aa)
    


  • @feiyuhuahuo
    I wonder whether: you have just added a new widget, but perhaps Qt has not yet recalculated the layout for that and so it has not adjusted horizontalScrollBar().maximum() to be a bigger value?

        def button_back(self):
            print(self.main_ui.scrollArea.horizontalScrollBar().maximum())
            self.marquees_layout.addWidget(self.marquee_label())
            print(self.main_ui.scrollArea.horizontalScrollBar().maximum())
    

    Does the second print() show a greater value or the same value?

    You might test the principle by moving the horizontalScrollBar().setValue(horizontalScrollBar().maximum()) into a QTimer::singleShot(), which you set off after the addWidget(), to give it time to show and adjust the scrollbar for the new widget. If that works you can then find a better way of recognising the added widget.



  • @JonB said in How to keep horizontalScrollBar at the rightmost side?:

    QTimer::singleShot()

    @JonB
    I tried your code, and the second value is the same as the first one.
    I also tried code:

        def print_max(self):
            print(self.main_ui.scrollArea.horizontalScrollBar().maximum())
    
        def button_back(self):
            QTimer.singleShot(50, self.print_max)
            self.marquees_layout.addWidget(self.marquee_label())
            QTimer.singleShot(50, self.print_max)
            QTimer.singleShot(50, self.print_max)
            QTimer.singleShot(50, self.print_max)
    

    All the values are the same.
    And yet I also tried:

        def button_back(self):
            self.marquees_layout.addWidget(self.marquee_label())
            # aa = self.main_ui.scrollArea.horizontalScrollBar().maximum()
            self.main_ui.scrollArea.horizontalScrollBar().setValue(99999)
    

    The result is the same. There's still some space left and the space is always just for a Qlabel.


Log in to reply