[PyQt] QMetaObject::Connection equivalent

Kyle Altendorf sda at fstab.net
Fri Dec 15 01:59:33 GMT 2017


On 2016-03-02 10:09, Florian Bruhin wrote:
> Hi,
> 
> I just noticed Qt5 returns a QMetaObject::Connection object when using
> QObject::connect:
> 
> http://doc.qt.io/qt-5/qobject.html#connect-2
> http://doc.qt.io/qt-5/qmetaobject-connection.html
> 
> You can then use that with the appropriate QObject::disconnect method
> to disconnect e.g. lambdas easily again:
> 
> http://doc.qt.io/qt-5/qobject.html#disconnect-4
> 
> I'm missing something like that in Python - it'd be nice to be able to
> do something like this:
> 
>     w = QTextEdit()
>     connection = w.textChanged.connect(lambda text: None)
>     # [...]
>     w.textChanged.disconnect(connection)
> 
> 'connection' then would be some pyqtSignalConnection object which
> pyqtSignal.disconnect understands.
> 
> Alternatively (or in addition to the above), disconnect could be a
> method of pyqtSignalConnection:
> 
>     w = QTextEdit()
>     connection = w.textChanged.connect(lambda text: None)
>     # [...]
>     connection.disconnect()
> 
> This would make it easier to work with Python lambda's and
> pyqtSignals.
> 
> What do you think?

Seems like it would be nice.  Is there no other interest in this (old) 
topic?  I made a little workaround class.

https://gist.github.com/altendky/1f95db4924732341d945b04157c6e94a
```
class Connection:
     def __init__(self, signal, slot):
         signal.connect(slot)
         self.signal = signal
         self.slot = slot

     def disconnect(self):
         self.signal.disconnect(self.slot)
```

Used like `Connection(obj_a.signal, obj_b.slot)`.  Seems like something 
along these lines could be returned by `pyqtSignal.connect()`.  If not a 
'real' `QMetaObject::Connection`.  Perhaps it would be appropriate to 
use weakrefs, I'm not certain.

Cheers,
-kyle


More information about the PyQt mailing list