PyQt: is there an better way to set objectName in code?

Question:

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.

Example:

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

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

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.

Asked By: bfris

||

Answers:

You can pass objectName as a keyword argument when creating the button.

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

This 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)

The added named argument is equivalent to button1.clicked.connect(someMethod)

Answered By: jonspaceharper
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.