What is the meaning of the brackets in the code line 'combo.activated[str].connect(self.onActivated)' for pyside?

pyside, python, qt

Solution

Here, `activated` is an overloaded signal, and `[str]` is indexing to the `str`-typed overload.

The signal is overloaded for the same reason a function is considered overloaded in C++: There are two functions with the same name, taking different parameters:

void QComboBox::activated ( int index ) [signal]
void QComboBox::activated ( const QString & text ) [signal]

Python doesn't have the strongly-typed function overloading that C++ has. So instead, PyQt handles this by having a dictionary of slots to which you can connect. The key to this dictionary is the `type` of the argument your handle will accept.

This example on the page that wastl linked to describes it well:

from PyQt4.QtGui import QComboBox

class Bar(QComboBox):

    def connect_activated(self):
        # The PyQt4 documentation will define what the default overload is.
        # In this case it is the overload with the single integer argument.
        self.activated.connect(self.handle_int)

        # For non-default overloads we have to specify which we want to
        # connect.  In this case the one with the single string argument.
        # (Note that we could also explicitly specify the default if we
        # wanted to.)
        self.activated[str].connect(self.handle_string)

    def handle_int(self, index):
        print "activated signal passed integer", index

    def handle_string(self, text):
        print "activated signal passed QString", text

Further Reading:

- PyQt and Signal Overloads (Blogspot)

- Connecting an overloaded PyQT signal using new-style syntax (Stack Overflow)

Problem

In a pyside tutorial I see the following line in the QtGui.QComboBox example: ``` combo.activated[str].connect(self.onActivated) ``` What does the expression `[str]` mean in this context? This is neither explained in the example, not on the pyside documentation. And also from the original Qt documentation it is not clear what the expression `[str]` actually means. I am well aware of indexing lists and dictionaries, but in the given context it seems a class method is indexed.

Original source

Related problems