Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pyqt

pyqt5

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.

like image 713
bfris Avatar asked Jun 06 '18 17:06

bfris


People also ask

What is setObjectName in PyQt5?

In this article we will see how we can set the object name of the spin box, object name is basically name given to the object of spin box, when we find the object in the PyQt5 application with the help of object name with the help of findChild method. In order to do this we will use setObjectName method..

What is QWidget in PyQt5?

The QWidget widget is the base class of all user interface objects in PyQt5. We provide the default constructor for QWidget . The default constructor has no parent. A widget with no parent is called a window.

What is canvas in PyQt5?

PyQt canvas for displaying Matplotlib plots. This module provides a PyQt canvas for Matplotlib to render its plots on. The canvas supports zooming and displays cursor position in axes coordinates as the cursor moves across the canvas. A plot window is an object of the QWidget class.

What is layout in PyQt?

In PyQt, layout managers are classes that provide the required functionality to automatically manage the size, position, and resizing behavior of the widgets in the layout. With layout managers, you can automatically arrange child widgets within any parent, or container, widget.


1 Answers

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

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)

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

like image 148
jonspaceharper Avatar answered Oct 14 '22 08:10

jonspaceharper