使QSpinBox.valueChanged()仅响应鼠标滚轮

时间:2015-09-08 11:22:51

标签: qt pyqt4

我有QSpinBox的信号valueChanged连接到QWidget的功能,如:

class MyWidget(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        #just an example
        mySpinBox = QtGui.QSpinBox()
        mySpinBox.valueChanged.connect(self.foo)

   def foo(self):
       if value was changed by Mouse Wheel:
            #do this
       else:
            #do nothing 

2 个答案:

答案 0 :(得分:1)

导出QSpinBox并覆盖wheelevent

http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html#wheelEvent

您可以定义自己的信号,该信号将由wheelevent发出以获得您想要的行为。

有关示例/教程,请参阅: http://pythoncentral.io/pysidepyqt-tutorial-creating-your-own-signals-and-slots/

答案 1 :(得分:0)

基于Gombat's回答和this问题(因为在提供的教程中如何解释它会引发错误)我在小部件中执行此操作

class MyWidget(QtGui.QWidget):
    mySignal1 = QtCore.pyqtSignal() #these have to be here or... 
    mySignal2 = QtCore.pyqtSignal() #...there will be an attribute error

    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        #just an example
        self.mySpinBox1 = QtGui.QSpinBox()
        self.mySpinBox2 = QtGui.QSpinBox()
        self.mySpinBox1.installEventFilter(self)
        self.mySpinBox2.installEventFilter(self)
        self.mySignal1.connect(self.foo)
        self.mySignal2.connect(self.bar)

   def eventFilter(self, source, event):
       if source is self.spinBox1:
           if event.type() == QtCore.QEvent.Wheel:
                self.spinBox1.wheelEvent(event)
                self.mySignal1.emit()
           return True
       else:
           return False
    elif source is self.spinBox2:
        if event.type() == QtCore.QEvent.Wheel:
            self.spinBox2.wheelEvent(event)
            self.mySignal2.emit()
            return True
        else:
            return False
    else:
        return QtGui.QWidget.eventFilter(self, source, event)

    def foo(self):
        #right here, when a mouse wheel event occured in spinbox1

    def bar(self):
        #right here, when a mouse wheel event occured in spinbox2
希望这会有所帮助。谢谢(未经测试,因为它只是一个例子,可能有错误)