PySide (or PyQt) Signals and Slot Machine Basics

advertisements

Consider a simple example like this which links two sliders using signals and slots:

from PySide.QtCore import *
from PySide.QtGui import *
import sys

class MyMainWindow(QWidget):
 def __init__(self):
  QWidget.__init__(self, None)

  vbox = QVBoxLayout()

  sone = QSlider(Qt.Horizontal)
  vbox.addWidget(sone)

  stwo = QSlider(Qt.Horizontal)
  vbox.addWidget(stwo)

  sone.valueChanged.connect(stwo.setValue)

if __name__ == '__main__':
 app = QApplication(sys.argv)
 w = MyMainWindow()
 w.show()
 sys.exit(app.exec_())

How would you change this so that the second slider moves in the opposite direction as the first? Slider one would be initialized with these values:

  sone.setRange(0,99)
  sone.setValue(0)

And slider two would be initialized with these values:

  stwo.setRange(0,99)
  stwo.setValue(99)

And then the value of stwo would be 99 - sone.sliderPosition.

How would you implement the signal and slot to make this work? I would appreciate a working example that builds on the simple example above.


Your example is a bit broken, because you forgot to set the parent of the layout, and also to save the slider widgets as member attributes to be accessed later... But to answer your question, its really as simple as just pointing your connection to your own function:

class MyMainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self, None)

        vbox = QVBoxLayout(self)

        self.sone = QSlider(Qt.Horizontal)
        self.sone.setRange(0,99)
        self.sone.setValue(0)
        vbox.addWidget(self.sone)

        self.stwo = QSlider(Qt.Horizontal)
        self.stwo.setRange(0,99)
        self.stwo.setValue(99)
        vbox.addWidget(self.stwo)

        self.sone.valueChanged.connect(self.sliderChanged)

    def sliderChanged(self, val):
        self.stwo.setValue(self.stwo.maximum() - val)

Note how sliderChanged() has the same signature as the original setValue() slot. Instead of connecting one widget directly to the other, you connect it to a custom method and then transform the value to what you want, and act how you want (setting a custom value on stwo)