[파이썬] PyQt 슬라이더 (`QSlider`) 위젯

In this blog post, we will explore how to use the QSlider widget from the PyQt library in Python. The QSlider widget is a versatile input control that allows users to select a value by dragging a slider handle along a range of values.

Installation

Before we get started, let’s make sure PyQt is installed on your machine. You can install it using pip:

pip install pyqt5

Creating a Simple QSlider Widget

Let’s start by creating a basic QSlider widget with a minimum and maximum value. We will also add labels to indicate the minimum and maximum values:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSlider, QLabel, QVBoxLayout

class SliderExample(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.slider = QSlider()
        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setRange(0, 100)
        self.slider.setTickInterval(10)
        self.slider.setSingleStep(1)

        self.labelMin = QLabel('Min')
        self.labelMax = QLabel('Max')

        vbox = QVBoxLayout()
        vbox.addWidget(self.labelMin)
        vbox.addWidget(self.slider)
        vbox.addWidget(self.labelMax)

        self.setLayout(vbox)
        self.setWindowTitle('QSlider Example')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SliderExample()
    ex.show()
    sys.exit(app.exec_())

In the above code, we create a custom SliderExample widget derived from QWidget. We initialize the QSlider, set its orientation to horizontal, and define the minimum and maximum values. We also set the tick interval and the single step, which defines how much the slider will move with each step. Lastly, we add labels for the minimum and maximum values, and arrange all the widgets in a vertical layout.

Handling QSlider Signals

The QSlider widget emits several signals that we can connect to custom slots to perform certain actions. For example, we can connect the sliderMoved signal to update a label with the current value of the slider:

self.slider.sliderMoved.connect(self.updateLabel)

def updateLabel(self, value):
    self.label.setText(f'Value: {value}')

In the above code snippet, every time the value of the slider changes, the sliderMoved signal is emitted, and the connected updateLabel method is called. The method updates the label text with the current value of the slider.

Conclusion

The QSlider widget is a powerful tool for allowing users to adjust values in a graphical interface. In this blog post, we’ve learned how to create and customize a QSlider widget, as well as how to handle its signals to perform certain actions.

Please refer to the PyQt documentation for more information and additional features of the QSlider widget. Happy coding with PyQt!