What kind of kwargs can you pass to a QObject during initialization?

Viewed 211

I noticed that in PyQt5, when initializing a QObject, you can pass it keywords to establish certain connections, dependent on the object. I think this is very useful, as it not only saves you a second statement, so you also don't need to reference the object explicitly if you don't have to, but more importantly, there may be situations in which it would be very cumbersome to do so. E.g. if you want to create a list of objects it could save you a loop and so on.

So in the case of QActions for example, you could do this:

from PyQt5.QtWidgets import QAction
from PyQt5.QtCore import pyqtSlot


@pyqtSlot()
def do_something():
    pass


@pyqtSlot()
def do_something_else():
    pass


actions = [QAction(triggered=do_something), QAction(triggered=do_something_else)]

But I only found this behaviour by chance. I couldn't find this being documented anywhere. E.g. in the official Qt documentation, no keywords are mentioned (QObject, QAction). Are there more things like this that you can do with QObjects during the initialization?

I don't understand why this is not documented. Is it not recommended maybe? I use PyCharm as an editor, and even though I know there are problems with it when it comes to syntax inspection, especially with regards to PyQt, it also highlights these keywords as 'unexpected arguments'.

1 Answers

In section Support for Qt Properties of PyQt5 docs indicates what type of data supports the keyword arguments:

PyQt5 does not support the setting and getting of Qt properties as if they were normal instance attributes. This is because the name of a property often conflicts with the name of the property’s getter method.

However, PyQt5 does support the initial setting of properties using keyword arguments passed when an instance is created. For example:

act = QAction("&Save", self, shortcut=QKeySequence.Save,
        statusTip="Save the document to disk", triggered=self.save) 

The example also demonstrates the use of a keyword argument to connect a signal to a slot.

PyQt5 also supports setting the values of properties (and connecting a signal to a slot) using the pyqtConfigure() method. For example, the following gives the same results as above:

act = QAction("&Save", self)
act.pyqtConfigure(shortcut=QKeySequence.Save,
        statusTip="Save the document to disk", triggered=self.save)

(emphasis mine)

In conclusion, you can set the kwargs:

  • The initialization of the qproperties, and
  • The slot with which the signals are connected
Related