我正在创建一个GUI,其中有一些滑块。我希望每个QSlider只能被拖动。有时,如果单击QSlider的任何部分,则滑块的位置都会改变。我该如何阻止这种情况发生?
答案 0 :(得分:0)
解决方案是验证当您不使用鼠标在滑槽中按下时:
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_())