Search code examples
pythonqtpyqtsignals-slots

What is the asterisk for in signal and slot connections?


In Python Qt, I'm connecting a QListWidget signal to a slot, like this:

QtCore.QObject.connect(self.myList, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.ListEventHandler)

My question is: what does the trailing asterisk in QListWidgetItem * do?


Solution

  • A couple of bullet points to explain (I'll try to avoid C++ syntax):

    • PyQt is a Python wrapper around Qt, which is written in C++.
    • Qt provides introspection for classes inheriting from QObject, frequently using strings to identify things. Python has native introspection, but C++ does not.
    • The syntax that you used is called "Old-Style Signals and Slots", which uses the C++ function signatures.
    • C++ has more types of variables than Python. In C++, a variable can be a value, reference, or pointer. Pointers have an asterisk after their type name.
    • QtCore.SIGNAL("itemClicked(QListWidgetItem *)") refers to a Qt signal called itemClicked that has a parameter that is a pointer to a QListWidgetItem, not the item itself.

    In C++, this looks like:

     void itemClicked(QListWidgetItem *item);
    

    Going back to strings for introspection, to identify a signal or slot, you drop the void, the ;, and the variable name (item), leaving:

     itemClicked(QListWidgetItem *)
    

    Wrap the above in QtCore.SIGNAL() and a pair of quotes and you have:

    QtCore.SIGNAL("itemClicked(QListWidgetItem *)")
    

    What is a pointer?
    There are a number of SO questions about this. Here is one with a number of analogies in the answers to simplify things for you.

    If this is old-style syntax, what's new style?
    Thanks to Frodon for bringing this up. PyQt has a more "pythonic" method of connecting signals to slots, in the format:

    object.signalName.connect(otherObject.slotName)
    

    In this case:

    self.myList.itemClicked.connect(self.ListEventHandler)
    

    Read more in the docs.