In PyQt5, How we get the name/Object name of the focus widgets?

Viewed 3202

In Our PyQt5 Programme, we use Qline Edits, QcheckBox, QListwidget several times.

How to know:

  1. What are the widgets used in Our Programme with Widget names ?
  2. How to get/returns the name of the widget(user-assigned name) which currently has the focus
1 Answers

As @Heike suggested, you can get a reference to the widget that has focus with QApplication.focusWidget

Depending on how your widgets are created, they might not have an objectName. If you use a GUI like Designer or Creator to drop your widgets on a form, then you will have the object name set. However, if you are creating your form in code, you may not have objectName set at all. In that case, you can just make sure to set the objectName in your code. You can see this question of mine for a discussion of setting objectName but to cut to the chase, you can use objectName as a keyword argument when you declare your widget in code, e.g.:

self.MyWidget = QWidget(objectName = MyWidget)

and later on if you want to get name of the widget that has focus you would use

widgetname = self.focusWidget().objectName()

or you could just do something with the reference:

widget = self.focusWidget()
Related