pythonpycharmpyqt6qslider

PyQt6 Slider not moving


I'm having trouble with a horizontal slider in Python and PyQt6. I can't move the darn thing with my mouse. What could it be?

from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QHBoxLayout, QSlider
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QMainWindow
import sys


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(800, 600)
        slider = QSlider(Qt.Orientation.Horizontal, self)
        slider.setGeometry(10, 480, 400,20)
        slider.setMinimum(0)
        slider.setMaximum(250)
        slider.setTickInterval(1)
        slider.valueChanged.connect(self.display)
        slider.setValue(0)
        widget = QWidget(slider)
        self.setCentralWidget(widget)

    def display(self):
        print(self.sender().value())


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

This should work right? Is this a package problem? I'm using PyCharm and Win11

I tried a lot of examples from google but nothing works

EDIT: I can move the slider with PageUP/Down buttons but not with the mouse


Solution

  • widget = QWidget(slider) is the culprit. I'm not sure what that is supposed to do.
    You can set the slider as centralwidget directly and it will work fine (but look a bit weird)

    Here's an example that puts the slider in a layout in a centralwidget. That may be more like what you intended to do.

    from PyQt6.QtCore import Qt
    from PyQt6.QtWidgets import QApplication, QWidget, QHBoxLayout, QSlider
    from PyQt6.QtWidgets import QMainWindow
    import sys
    
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.resize(800, 600)
            slider = QSlider(Qt.Orientation.Horizontal, self)
            slider.setGeometry(10, 480, 400, 20)
            slider.setMinimum(0)
            slider.setMaximum(250)
            slider.setTickInterval(1)
            slider.valueChanged.connect(self.display)
            slider.setValue(0)
            widget = QWidget()
            lay = QHBoxLayout(widget)
            lay.addWidget(slider)
            self.setCentralWidget(widget)
    
        @staticmethod
        def display(value):
            print(value)
    
    
    def main():
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec())