PyQt6: QEvent.type() returns int instead of QEvent.Type

Phil Thompson phil at riverbankcomputing.com
Fri May 13 09:43:07 BST 2022


On 03/05/2022 14:22, Florian Bruhin wrote:
> On Sun, May 01, 2022 at 03:13:12PM +0100, Phil Thompson wrote:
>> 
>> On 28/04/2022 20:16, Florian Bruhin wrote:
>> > On Thu, Apr 28, 2022 at 09:42:46AM +0100, Phil Thompson wrote:
>> > > So if we can solve the pickle problem I think I'd be Ok to take this
>> > > approach.
>> >
>> > I think the most elegant way to do this is via the _missing_ classmethod
>> > on enums. This is public API:
>> > https://docs.python.org/3/library/enum.html#supported-sunder-names
>> >
>> > The drawback about the approach is that it's possible to do
>> > SomePyQtEnum(1337) and that happily returns a value, so at this point,
>> > the cpp2py() can probably just be implemented in _missing_ altogether.
>> >
>> > See the attached file. The _missing_ method needs to use cpp2py so that
>> > even values which haven't been passed through cpp2py before work fine.
>> >
>> > This means I had to rewrite cpp2py slightly to avoid triggering
>> > _missing_. The __members__ attribute is documented too:
>> > https://docs.python.org/3/library/enum.html#iteration
>> >
>> > Alternatively, "if cpp in list(etype):" could be used, but that builds
>> > up an unnecessary list ("cpp in etype" will not work, raising a
>> > TypeError).
>> >
>> > If we didn't want to use missing (so that SomePyQtEnum(1337) does not
>> > work), I suppose it can be solved by defining __reduce_ex__ on the enum
>> > type somehow, but I tried, and it never was called (only enum.py's was).
>> 
>> I had come to the same conclusion that the only way to support pickle 
>> was to
>> use a sub-class of Enum and re-implement _missing_. I had hoped to be 
>> able
>> to use a regular Enum (and IntEnum).
> 
> You can register a pickle function via copyreg.pickle instead:
> https://docs.python.org/3/library/copyreg.html#copyreg.pickle
> 
> This seems to work:
> 
>     copyreg.pickle(SomePyQtEnum, lambda py: (cpp2py, (SomePyQtEnum,
> py2cpp(py))))
> 
> It's the equivalent of defining an equivalent __reduce__ on the class:
> SomePyQtEnum now gets pickled in a way that
> cpp2py(SomePyQtEnum, raw_value) is called when unpickling, where
> raw_value is py2cpp(py).
> 
> See the attached file for a complete example.

I've decided to go with the attached. I think it's the cleanest solution 
that deals with all the issues.

Phil
-------------- next part --------------
A non-text attachment was scrubbed...
Name: e4.py
Type: text/x-python
Size: 1232 bytes
Desc: not available
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20220513/d3e2207f/attachment.py>


More information about the PyQt mailing list