Show QT widget UI hierarchy

# -*- coding: utf-8 -*-
##  Copyright 2019 Trevor van Hoof and Jan Pijpers.
##  Licensed under the Apache License, Version 2.0
##  Downloaded from or
##  See the license file attached or on

Name: showQtWidgetHierarchy

In maya you sometimes want to hack the UI.
Seeng as the UI is made with QT you can hack into it by finding the right node and or widget name.

To make this process easier you can run this script and it will show you the entire hierarchy and return it as a dict


import json

import sys
from PySide.QtGui import * ## pip install PySide

def widgets_recursive(d, widget = None, doPrint =False ):
    if not widget:
        for widget in QApplication.topLevelWidgets():
            get_widget(widget, d, 0, doPrint)
        get_widget(widget, d, 0, doPrint)
def get_widget(w,d, depth = 0, doPrint=False):
        Recursively searches through all widgets down the tree and prints if desired.
    :param w: the widget to search from
    :param d: the dictionary to add it to
    :param depth: current depth we are at
    :param doPrint: if we need to print
    n = w.objectName()
    n = n if n else str(w)
    if doPrint: print "\t"*depth, n
    newD = {}
    for widget in w.children():
        get_widget(widget, newD, depth +1 )
    d[n] = newD

def get_widget_from_name(name):
    for widget in QApplication.allWidgets():
            if name in widget.objectName() :
                return widget
    return None 

if __name__ =="__main__":

    ## Remove this block if you are running this in maya or something.
    ## Here we make a simple QWindow with a layout and button.
    app = QApplication(sys.argv)
    wid = QWidget()
    button = QPushButton()
    button.setObjectName("This is my button, there are many like it but this one is mine.")
    lay = QHBoxLayout()

    ## Create a simpe dict to hold all the data in the ned.
    widgetHierarchyDict = {}

    ## if you have no idea where to start. Just leave the topWidget argument to None
    ## But if you are in a QT based aplication like Maya you can also start from a widget you know the name of to speed
    ## up the process
    widgetObjectName = None ## "graphEditor1Window"
    topWidget = get_widget_from_name(widgetObjectName)

    ## Recurse over all widgets and store all the information in the provided dict.
    widgets_recursive(widgetHierarchyDict, topWidget)

    ## Print it with json so its nice and clear.
    print json.dumps(widgetHierarchyDict, sort_keys=True, indent = 2 )

Leave a Reply
