Search code examples
pythonpyqtqgraphicssceneobject-type

pyqt. How do you know the type of object in QGraphicsScene?


i use pyqt4.8 + python2.7

in QGraphicsScene i add different objects like QGraphicsEllipseItem and QGraphicsProxyWidget (with QPushButton). To work with different types of objects have to call different functions.

such as changing the size of the object

for QGraphicsEllipseItem:

item.setRect(size)

for QPushButton:

item.widget().setRect(size)

ps. setRect() for QPushButton - is my custom function

I select objects in the scene and want to change their size. But for different objects need to call different functions and need to get like that type of object to cause then the desired function.

I got selected objects.

selItems = self.scene.selectedItems()
for item in selItems:
    ...

how to further learn what type of object to trigger the desired function?


Solution

  • You can use method type()

    selItems = self.scene.selectedItems()
    for item in selItems:
        obj_type = type(item)
    

    And check it with an if statement:

    if obj_type == QPushButton:
        # do stuff
    

    Or you can check it with isinstance() function.

    if isinstance(item, QPushButton):
        # do stuff
    

    I take QPushButton as an example, set the widget you want to check for.