7

This should be a stupid question. I am just curious and could not find the answer on my own.

E.g. I define in PyQt5 some widgets:

self.lbl = QLabel("label")
self.btn = QPushButton("click")
self.txt = QLineEdit("text")

Is there any method to detect what kind of widget the self.lbl, self.btn, or self.txt are?

I could imagine: by detecting the widget type, the input is self.lbl, the output should be QLabel... Or something like this.

I have only found the isWidgetType() method. But it is not what I want to have.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Rt Rtt
  • 595
  • 2
  • 13
  • 33

2 Answers2

13

There are several ways to get the name of the widget:

  • using __class__:

print(self.lbl.__class__.__name__)
  • using QMetaObject:

print(self.lbl.metaObject().className())

These previous methods return a string with the name of the class, but if you want to verify if an object belongs to a class you can use isinstance():

is_label = isinstance(self.lbl, QLabel)

Another option is to use type() but it is not recommended, if you want to get more information about isinstance() and type() read the following: What are the differences between type() and isinstance()?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
3

You can just use the standard Python means of checking an object type:

print(type(self.lbl))
print(isinstance(self.lbl, QLabel)
Turn
  • 6,656
  • 32
  • 41