本文介绍了PyQt:有没有更好的方法在代码中设置 objectName?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您使用 Qt_Designer 或 Qt_Creator 设计表单时,任何给定小部件的 objectName 始终设置为某个值.但是,如果您在代码中创建一个小部件并且稍后需要 objectName,则必须明确分配它.那么小部件分配至少需要两行代码.这看起来很不雅.

When you use Qt_Designer or Qt_Creator to design a form, objectName for any given widget is always set to something. But if you create a widget in code AND you need the objectName later, you have to assign it explicitly. So then the widget assignment takes at least two lines of code. This seems very inelegant.

示例:

button1 = QPushButton('button caption')   # at this point objectName is some kind of empty string
button1.setObjectName('button1')

如果您稍后需要找到该小部件(即使用 findChild),您必须设置 objectName,否则您就不走运了.

If you need to find the widget later (i.e. with findChild), you must have objectName set, otherwise you're out of luck.

有什么方法可以不用额外的代码行自动设置 objectName 吗?我查看了 PyQt5 参考指南,但找不到这样的功能.一个 类似的问题被问到 关于代码审查,但没有得到答复.两行代码并不是世界末日,但似乎是多余的.不知何故,我需要为 Python(第一行)和 Qt 两次分配这个名称.

Is there some way to automatically set objectName without extra lines of code? I looked at the PyQt5 Reference Guide and could not find such a feature. A similar question was asked on Code Review, but got no answers. Two lines of code isn't the end of the world, but it seems redundant. Somehow I'm required to assign this name twice once for Python (first line) and again for Qt.

推荐答案

button1 = QPushButton('button caption', objectName='button1')

您可以在初始化期间将此扩展到任何 Qt 属性:

You can extend this to any Qt property during initialization:

button1 = QPushButton(text='button caption', objectName='button1', icon=icon1)

此外,在构造对象时也可以连接信号:

Moreover, signals can be connected when constructing an object, too:

button1 = QPushButton(text='button caption', objectName='button1', clicked=someMethod)

添加的命名参数相当于button1.clicked.connect(someMethod)

这篇关于PyQt:有没有更好的方法在代码中设置 objectName?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 05:12