问题描述
效果如图:
上侧的Slider是普通的Slider, 下侧的Slider是背景不可点击的Slider
解决方法
继承QSlider的类,重写mousePressEvent方法,加入点击区域判断就行了。Slider的背景在PySide2/Qt 里叫groove,就是凹槽的意思。
from PySide2 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)
加上测试代码
from PySide2 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_())