Find item in QApplication by only the objectname

后端 未结 3 598
南方客
南方客 2021-01-03 16:14

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

Something like

QApplication.instance().findByClassName(\"codeEditor         


        
3条回答
  •  被撕碎了的回忆
    2021-01-03 16:36

    In Python, this can be done for any class using the gc module. It provides a method for retrieving the references of all objects tracked by the garbage-collector. This is obviously a quite inefficient approach, but it does (almost) guarantee that any type of object can be found.

    Here's a function to get a list of all QObject instances either by class-name or object-name:

    def getObjects(name, cls=True):
        objects = []
        for obj in gc.get_objects():
            if (isinstance(obj, QtCore.QObject) and
                ((cls and obj.inherits(name)) or
                 (not cls and obj.objectName() == name))):
                objects.append(obj)
        return objects
    

    This is only really a debugging tool, though - for a large application, there could easily be several hundred thousand objects to check.

    If you only need objects which are subclasses of QWidget, use this function:

    def getWidgets(name, cls=True):
        widgets = []
        for widget in QtGui.QApplication.allWidgets():
            if ((cls and widget.inherits(name)) or
                (not cls and widget.objectName() == name)):
                widgets.append(widget)
        return widgets
    

    PS:

    If you want to find all objects which are subclasses of QObject, this can only be achieved if you can somehow ensure that all the instances in your application have a valid parent (which, by definition, must also be a QObject). With that in place, you can then use root_object.findChildren(QObject) to get the full list. It is also possible to use findChild or findChildren to search for individual objects by object-name (optionally using a regular-expression, if desirable).

提交回复
热议问题