0

I'm creating a GUI where I have a few sliders. I want each QSlider such that it can only be dragged. Sometimes, if I click on any part of a QSlider, the position of the slider changes. How can I stop that from happening?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Kaya311
  • 545
  • 2
  • 9
  • 21

1 Answers1

0

The solution is to verify that when you do not press with the mouse in the slider groove:

from PyQt5 import QtCore, QtWidgets


class SliderUnclickable(QtWidgets.QSlider):
    def mousePressEvent(self, event):
        opt = QtWidgets.QStyleOptionSlider()
        self.initStyleOption(opt)
        pressedControl = self.style().hitTestComplexControl(QtWidgets.QStyle.CC_Slider, opt, event.pos(), self)
        if pressedControl != QtWidgets.QStyle.SC_SliderGroove:
            super(SliderUnclickable, self).mousePressEvent(event)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    flay = QtWidgets.QFormLayout(w)
    w1 = QtWidgets.QSlider(QtCore.Qt.Horizontal)
    w2 = SliderUnclickable(QtCore.Qt.Horizontal)
    flay.addRow("default QSlider: ", w1)
    flay.addRow("SliderUnclickable: ", w2)
    w.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241