仅通过对象名在QApplication中查找项目 [英] Find item in QApplication by only the objectname

查看:108
本文介绍了仅通过对象名在QApplication中查找项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在QApplication中通过对象名字符串名称找到任何对象

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

类似

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 *

这是我想测试的东西:

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

它甚至都没有找到明显位于其中的'InfoFrame':

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

>>> widget("info")

{}

推荐答案

我想到了这个效果很好的

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

这篇关于仅通过对象名在QApplication中查找项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆