Search code examples
pythonqtpyqtteamspeakpythonqt

Find item in QApplication by only the objectname


i want to find any object by a objectname string name inside of the QApplication

Something like

QApplication.instance().findByClassName("codeEditor")

which should return a list of widgets with this classname that i can iterate over if there is more then one

[QPushButton (QPushButton at: 0x0000008EA3B3DD80), QWidget (QWidget at: 0x0000008EA3F33F40)]

I have read this but it requires a object and i want something like *

This is something i came up with for testing:

def findWidget(name):
    name = name.lower()
    widgets = self.topLevelWidgets()
    widgets = widgets + self.allWidgets()
    ret = dict()
    c = 0
    for x in widgets:
        c += 1
        if name in x.objectName.lower() or name in str(x.__class__).lower():
            ret["class:"+str(x.__class__)+str(c)] = "obj:"+x.objectName;continue
        if hasattr(x, "text"):
            if name in x.text.lower():
                ret["class:"+str(x.__class__)+str(c)] = "obj:"+x.objectName
    return ret

It doesn't even find the 'InfoFrame' which is clearly there:

>>> widget("info")


{}

enter image description here


Solution

  • I came up with this which works quite well

    def getWidgetByClassName(name):
        widgets = QApplication.instance().topLevelWidgets()
        widgets = widgets + QApplication.instance().allWidgets()
        for x in widgets:
            if name in str(x.__class__).replace("<class '","").replace("'>",""):
                return x
    def getWidgetByObjectName(name):
        widgets = QApplication.instance().topLevelWidgets()
        widgets = widgets + QApplication.instance().allWidgets()
        for x in widgets:
            if str(x.objectName) == name:
                return x
    def getObjects(name, cls=True):
        import gc
        objects = []
        for obj in gc.get_objects():
            if (isinstance(obj, PythonQt.private.QObject) and
                ((cls and obj.inherits(name)) or
                 (not cls and obj.objectName() == name))):
                objects.append(obj)
        return objects