PyQt5 QScrollBar - Value Changed Signal

PyQt5 QScrollBar - Value Changed Signal

In PyQt5, QScrollBar is a widget that provides a vertical or horizontal scroll bar. The QScrollBar widget emits a signal called valueChanged whenever the value of the scrollbar changes. This signal can be connected to a slot (a function or a method) to perform an action whenever the scrollbar's value is altered, either by user interaction or programmatically.

Here's an example demonstrating how to use the valueChanged signal with a QScrollBar:

Step 1: Import PyQt5 Modules

First, import the necessary PyQt5 modules.

import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QScrollBar, QLabel from PyQt5.QtCore import Qt 

Step 2: Create the Main Window and Add QScrollBar

Create a main window class, add a QScrollBar widget to it, and connect the valueChanged signal to a custom slot.

class MainWindow(QMainWindow): def __init__(self): super().__init__() # Create QScrollBar self.scroll_bar = QScrollBar(Qt.Horizontal, self) self.scroll_bar.setMaximum(100) # Create a QLabel to display the value self.label = QLabel("0", self) self.label.move(200, 20) # Connect the valueChanged signal to the custom slot self.scroll_bar.valueChanged.connect(self.on_value_changed) # Set geometry of the main window and the scrollbar self.setGeometry(100, 100, 400, 100) self.scroll_bar.setGeometry(20, 20, 160, 30) def on_value_changed(self, value): # Update the label text when the scrollbar value changes self.label.setText(str(value)) def main(): app = QApplication(sys.argv) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) if __name__ == "__main__": main() 

In this example:

  • The MainWindow class creates a horizontal QScrollBar and a QLabel.
  • The valueChanged signal of QScrollBar is connected to the on_value_changed slot.
  • The on_value_changed function updates the text of the QLabel to reflect the current value of the scrollbar.

Step 3: Run the Application

Run the application. A window with a scrollbar and a label will appear. When you move the scrollbar, the label will update to display the scrollbar's current value.

This example provides a basic demonstration of using QScrollBar and its valueChanged signal. You can extend this functionality to suit the specific needs of your application, such as updating the view of a widget based on the scrollbar's position.


More Tags

python-2.x spring-mvc pymysql excel bounding-box alphabet gridpanel dropbox spring-boot azure-cosmosdb-sqlapi

More Programming Guides

Other Guides

More Programming Examples