# Written by Robin Burchell
# No licence specified or required, but please give credit where it's due, and please let me know if this helped you.
# Feel free to contact with corrections or suggestions.
#
# We're using PySide, Nokia's official LGPL bindings.
# You can however easily use PyQt (Riverside Computing's GPL bindings) by commenting these and fixing the appropriate imports.
from PySide.QtCore import *
from PySide.QtGui import *
#from PyQt4 import *
#from PyQt4.QtCore import *
#from PyQt4.QtGui import *
import sys
class MyMainWindow(QWidget):
def __init__(self):
QWidget.__init__(self, None)
vbox = QVBoxLayout()
# Let's create two sliders widgets.
# http://doc.trolltech.com/4.6/qslider.html
sone = QSlider(Qt.Horizontal)
vbox.addWidget(sone)
stwo = QSlider(Qt.Horizontal)
vbox.addWidget(stwo)
# Link the first slider to the second.
# Think of this as an event and listener system - a signal is an event, and it can have multiple listeners.
# A slot is a listener to an event.
#
# Signals are generally used whenever an action occurs which might require a reaction, or feedback - for example,
# a user clicking on a button, or a slider value changing.
#
# A signal can provide one (or more) parameters, which can then be used in the corresponding slot(s).
#
# In this example, we're linking the valueChanged signal to setValue on the second slider, meaning that whenever the
# first slider is moved, the second slider will move with it.
#
# This might look strange when compared with the .NET and other typical methods of doing it, but it
# really is much more natural and easier to express.
# See also:
# http://doc.trolltech.com/4.6/signalsandslots.html
self.connect(sone, SIGNAL("valueChanged(int)"), stwo, SLOT("setValue(int)"));
# Set the layout on the window: this means that our button will actually be displayed.
self.setLayout(vbox)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyMainWindow()
w.show()
app.exec_()
sys.exit()
Tuesday, 9 February 2010
Simple PySide tutorial, #2: signals and slots
Second tutorial for PySide, this time focusing on Qt's signals and slots system, trying to provide a simple example of how they can be chained together to provide simpler code.
| Reactions: |
Subscribe to:
Post Comments (Atom)
2 comments:
Thanks!
A small addition to this code could be adding a 3rd slider which would be mirroring the movements of the first slider. I tried to do it, and found out that I need to lear more about the signals and slots (I suspect that I need to implement my own slider class with "setMirrorValue" method which I would use as a slot, but I am not sure if there is an easier way to achieve this...)
@hartti: hmm, the second slider should already be mirroring the first, so adding a third slider should be fairly straightforward.. unless I'm misunderstanding you?
sthree = QSlider(Qt.Horizontal)
vbox.addWidget(sthree)
self.connect(sone, SIGNAL("valueChanged(int)"), sthree, SLOT("setValue(int)"));
Post a Comment