Wednesday, September 1, 2010

Python Koans - A Great Way to Learn Python!

I just found out about Python Koans by Greg Malcolm (thanks dude) after listening to the from python import podcast podcast (which I find amusing, thanks guys).

It's an awesome way to learn Python. Instead of just reading tutorials and/or books you learn Python by coding.

The interactive tutorial is built around unit-tests and you advance and gain new skills by passing tests and it's really funny. You do learn a lot about the Python language when doing the Koans so I recommend it even if you've been using Python for a while.

Another cool thing is that you learn how to do unit testing in Python, if you're not already familiar with it.



Tuesday, August 3, 2010

My python fix

It has been a while since I did something in Python. I've been coding C++, Qt and Qt Quick lately and I do enjoy it, especially Quick. I really like the declarative way of describing UIs.

But I still need my shot of Python now and then. Often I end up just doing small non useful snippets like list comprehensions stuff. I just love them, they are so beautiful and they make me happy :)
>>> # Find the longest words
>>> words = "Some random words in a text string"
>>> max([(len(w), w) for w in words.split()], key=lambda x:x[0])[1]

Thursday, June 10, 2010

QSignalMapper - at your service

The QSignalMapper class is very useful, for example, in situations were you have a couple of QPushButtons and you want to connect the clicked-signal of each button to a single slot and still be able to identify the sender. It's possible to find out which object emitted a signal by calling sender() inside the slot, but I don't think that's good practice because you introduce a strong coupling between the signaling object and the slot.

A better solution is to use the QSignalMapper class which re-emits the signal with an additional configurable parameter. The parameter can be one of the following types: int, QString, QObject or QWidget.

So without further ado, here's a self describing example:
#
# Example showing how QSignalMapper can be used to manage an arbitrary
# numbers of parameterless signals and re-emit them with an argument
# identifying the sender.
#
# Each signal is associated in the QSignalMapper with either an int,
# QString, QObject or a QWidget which is passed as argument to the slot
# connected to the QSignalMapper.
#
from PyQt4.QtCore import QSignalMapper, pyqtSignal
from PyQt4.QtGui import QApplication, QFrame, QGridLayout, QPushButton

class Grid(QFrame):
    """ Lay out widgets in a grid. """

    clicked =  pyqtSignal(int)
    """
    This signal will be emitted when on one of the grid items is clicked.
    The grid item's index will be passed as argument.
    """

    def __init__(self, items, colCount, parent=None):
        """
        Create Grid and setup QSignalMapper.

        Connect each item's 'clicked' signal and use the sequence index
        as map value which will be passed as argument when the Grid's
        clicked signal is emitted.

        items: sequence with widgets having a 'void clicked()' signal
        colCount: column count for each row
        parent: parent widget, default None
        """
        super(Grid, self).__init__(parent)

        # Create a grid layout.
        layout = QGridLayout()
        self.setLayout(layout)

        # Create the signal mapper.
        signalMapper = QSignalMapper(self)

        for cnt, item in enumerate(items):
            # Setup mapping for the item. In this case, the
            # mapping is the sequence index of the item.
            signalMapper.setMapping(item, cnt)

            # Connect the item's 'clicked' signal to the signal
            # mapper's 'map' slot.
            # The 'map' slot will emit the 'mapped' signal
            # when invoked and the mapping set previously will be
            # passed as an argument to the slot/signal that is
            # connected to the signal mapper's 'mapped' signal.
            item.clicked.connect(signalMapper.map)

            # Add the widget to the grid layout
            layout.addWidget(item, cnt / colCount, cnt % colCount)

        # Forward the signal mapper's 'mapped' signal via the Grid's
        # 'clicked' signal. This will handle all widgets' 'clicked'
        # ssignals.
        signalMapper.mapped.connect(self.clicked)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)

    # Create grid items
    items = (QPushButton('Open'), QPushButton('Close'),
             QPushButton('Read'), QPushButton('Write'),
             QPushButton('Delete'))

    win = Grid(items, 2)

    # Handle grid clicks here
    @win.clicked.connect
    def clicked(index):
        print "Button at:", index, " - text:", items[index].text()

    win.show()
    sys.exit(app.exec_())
Hope this was to any help.