[PyQt] How to emit signal from QGraphicsRectItem

Vincent Vande Vyvre vincent.vande.vyvre at telenet.be
Fri Sep 4 01:40:40 BST 2015


Le 04/09/2015 00:14, michael h a écrit :
>
>
>
>
>     class RectItem(QGraphicsRectItem):
>         selectedChange = pyqtSignal(str)
>
>     And I got error:
>     test3.py, line 48, in <module>
>         rect.selectedChange.connect(message)
>     TypeError: RectItem cannot be converted to PyQt5.QtCore.QObject in
>     this context
>
>     How to solve this?
>
>     Zdenko
>
>
> Zdenko,
>
> QGraphicsRectItem does not inherit from QObject, while 
> QGraphicsTextItem does.
>
> See: 
> http://stackoverflow.com/questions/4922801/adding-signals-slots-qobject-to-qgraphicsitem-performance-hit
>
> The first answer alludes to either inheriting directly from 
> QGraphicsObject, or using multiple inheritance e.g. 
> SomeItem(QGraphicsRectItem, QObject) but i'm not sure this works from 
> python.
>
> The second answer listed hints at a signal emitting QObject that can 
> emit signals on behalf of the RectItems.
>
> - mh
>
>
> _______________________________________________
> PyQt mailing list    PyQt at riverbankcomputing.com
> https://www.riverbankcomputing.com/mailman/listinfo/pyqt
I use this method in this case:

---------------------------------
class RectItem(QGraphicsRectItem):
     def __init__(self, parent=None):
         super(RectItem, self).__init__(-30, -30, 30, 30, parent)
         pen = QPen(Qt.red, 2, Qt.SolidLine,
                    Qt.RoundCap, Qt.RoundJoin)
         self.setPen(pen)
         self._selectedChange = SelectedChange()

     def selectedChange():
         def fget(self):
             return self._selectedChange.selectedChange
         return locals()
     selectedChange = property(**selectedChange())

     def mousePressEvent(self, event):
         self.selectedChange.emit('RectItem')
         super(RectItem, self).mousePressEvent(event)

class SelectedChange(QObject):
     selectedChange = pyqtSignal(str)
     def __init__(self):
         super(SelectedChange, self).__init__()
-------------------------------------

Others QGraphicsItems can share the same signal, if the the signature is 
the same of course.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20150904/1283078f/attachment.html>


More information about the PyQt mailing list