[PyQt] How to add an argument to derived class's constructor

J Barchan jnbarchan at gmail.com
Thu Feb 14 13:34:31 GMT 2019


This may be as much a Python question as a PyQt one.  I come from a C++
background.  I do not understand the syntax/code I need in a class I am
deriving from a PyQt class to allow a new parameter to be passed to the
constructor.

I see that I asked this question a long time ago at
https://stackoverflow.com/questions/45999732/python3-typing-overload-and-parameters
but never got an answer.

I now want to sub-class from QListWidgetItem.  That starts with these
constructors:

QListWidgetItem(QListWidget *parent = nullptr, int type = Type)
QListWidgetItem(const QString &text, QListWidget *parent = nullptr, int
type = Type)
QListWidgetItem(const QIcon &icon, const QString &text, QListWidget *parent
= nullptr, int type = Type)
QListWidgetItem(const QListWidgetItem &other)

My sub-class should still support these constructors.  In addition to the
existing text, I want my sub-class to be able to store a new optional value.
At minimum/sufficient I want a new possible constructor like one of the
following:

MyListWidgetItem(const QString &text, const QVariant &value, QListWidget
*parent = nullptr, int type = Type)
# or
MyListWidgetItem(const QString &text, QVariant value = QVariant(), QListWidget
*parent = nullptr, int type = Type)

So for Python I know I start with a *typing overload* definition (for my
editor) like

@typing.overload
def MyListWidgetItem(self, text: str, value: typing.Any, parent:
QListWidget=None, type: int=Type)
    pass

Then I get to the *definition* bit.  To cater for everything am I supposed
to do:

def __init__(self, *__args)
    # Now what??
    super().__init__(__args)

Is that how we do it?  Is it then my responsibility to look at __args[1] to
see if it's my value argument?  And remove it from __args before passing it
onto super().__init__(__args)?

Or, am I not supposed to deal with __args, and instead have some definition
with all possible parameters explicitly and deal with them like that?

Or what?  This is pretty fundamental to sub-classing to add parameters
where you don't own the code of what you're deriving from.  It's easy in
C-type languages; I'm finding it real to hard to understand what I
can/can't/am supposed to do for this, I'd be really gratefully for a couple
of lines to show me, please...! :)

-- 
Kindest,
Jonathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20190214/8d1ca71c/attachment.html>


More information about the PyQt mailing list