1

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

3 Answers3

1

Does this help?

How to obtain an instance's name at runtime?

Sujith Surendranathan
  • 2,569
  • 17
  • 21
1

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.

Nikita Nemkin
  • 2,780
  • 22
  • 23
0

A general answer (with example). Let's say we have a class Foo, and we want it to describe what it is called:

class Foo(object):
    def my_name_is(self):
        for name, obj in globals().items():
            if obj is self:
                print('My name is ' + repr(name))

bar = Foo()
bar.my_name_is()
# prints: My name is 'bar'

This works perfectly is you have only one copy of that object. However, if you copy it, then it can have multiple names:

other_bar = bar
other_bar.my_name_is()
# prints two lines: My name is 'other_bar'
#                   My name is 'bar'
Mike T
  • 41,085
  • 18
  • 152
  • 203