Search code examples
pythonruntimepyqtstylesheetinstance

Python: How to obtain an instance's name at runtime?


I'm using PyQt. And because I'm using Qt Style Sheets, I have to set object names to widgets which I want to specify in my style rules (e.g "#deleteButton { font-size: 14px; }"). In code, I have to do:

...
self.deleteButton = QToolButton(self)
self.deleteButton.setObjectName("deleteButton")
...

But I would to do:

...
self.deleteButton = QToolButton(self)
self.deleteButton.setObjectName(self.deleteButton.__give_my_instance_name__)
...

If I find a way, I can apply it to all widgets in the container.

Thanks in advance


Solution

  • What you're trying to accomplish is better done with this code:

    for name, obj in self.__dict__.iteritems():
        if isinstance(obj, QtCore.QObject) and not obj.objectName(): # QObject without a name
            obj.setObjectName(name)
    

    Use it at the end of your object creation routine.