I am trying to make a LabeledSlider
class that has all the logic for my slider contained within itself. Whenever I instantiate multiple of this class it causes the sliders to interact with one another when I move any of the sliders. Please help me fix this issue. My code is:
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QSlider, QLabel, QVBoxLayout, QHBoxLayout, QWidget
from PyQt5.QtCore import Qt
class LabeledSlider(QWidget):
def __init__(self, header="Header", orientation=Qt.Horizontal, parent=None):
super().__init__(parent)
# Create the slider
self.slider = QSlider(orientation)
self.slider.valueChanged.connect(self.update_label)
# Create the header
self.header = QLabel(header)
self.header.setAlignment(Qt.AlignLeft)
# Create the label
self.label = QLabel('0')
self.label.setAlignment(Qt.AlignLeft)
# Create the layout and add widgets
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.header)
self.innerLayout = QHBoxLayout()
self.layout.addLayout(self.innerLayout)
self.innerLayout.addWidget(self.slider)
self.innerLayout.addWidget(self.label)
# Set the initial label value
self.update_label(self.slider.value())
def update_label(self, value):
self.label.setText(str(value))
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Labeled Slider Example')
# Create the layout and add labeled sliders
layout = QHBoxLayout()
left_layout = QVBoxLayout()
right_layout = QVBoxLayout()
layout.addLayout(left_layout)
layout.addLayout(right_layout)
# Left side
slider = LabeledSlider("Slider 1", Qt.Horizontal)
left_layout.addWidget(slider)
slider = LabeledSlider("Slider 2", Qt.Horizontal)
left_layout.addWidget(slider)
slider = LabeledSlider("Slider 3", Qt.Horizontal)
left_layout.addWidget(slider)
# Right side
slider = LabeledSlider("Slider 4", Qt.Horizontal)
right_layout.addWidget(slider)
slider = LabeledSlider("Slider 5", Qt.Horizontal)
right_layout.addWidget(slider)
slider = LabeledSlider("Slider 6", Qt.Horizontal)
right_layout.addWidget(slider)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
I am not sure where the error may be to start trying things.
New contributor
Alex StAubin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.