Python:如何在运行时获取实例的名称?

发布于 2024-10-09 19:13:18 字数 450 浏览 0 评论 0原文

我正在使用 PyQt。因为我使用的是 Qt 样式表,所以我必须将对象名称设置为我想要在样式规则中指定的小部件(例如“#deleteButton { font-size: 14px; }”)。 在代码中,我必须这样做:

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

但我会这样做:

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

如果我找到一种方法,我可以将其应用到容器中的所有小部件。

提前致谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

君勿笑 2024-10-16 19:13:18

您想要完成的事情最好使用以下代码来完成:

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

在对象创建例程结束时使用它。

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.

莫相离 2024-10-16 19:13:18

一般答案(带示例)。假设我们有一个类 Foo,并且我们希望它能够描述它的名称:

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'

如果您只有该对象的一个​​副本,则效果非常好。但是,如果复制它,则它可以有多个名称:

other_bar = bar
other_bar.my_name_is()
# prints two lines: My name is 'other_bar'
#                   My name is 'bar'

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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文