+1 vote

I have been trying to figure out how to get a reference to the theme that is being used (in GDscript), if the theme is propagated to the child by the parent.

Normally, to get the theme, you would simply call self.theme, but this gives an error (attempting to call null on null instance) indicating that the child does not have a theme (because we never specifically set one in the editor). But the child does use the Theme of its parent, but I'm unsure how to properly get this reference.

For example, I would be trying to figure out what Theme the PanelContainer is using.

Control -  *has a theme*
     Label -  *uses parent theme*
     PanelContainer - *uses parent theme*

Please keep in mind I won't know how far down the tree the child is, so a simple self.get_parent() won't do the trick here.

Thank you!

in Engine by (42 points)
edited by

1 Answer

+2 votes

I don't have much theme experience in Godot, so I don't know whether there's a more direct way to get what you're after, but here's a brute-force way of finding a defined theme somewhere up the tree from a specified node...

func _ready():
    var label = $Control/Label1/Label2
    print(get_theme(label))

func get_theme(control):
    var theme = null
    while control != null && "theme" in control:
        theme = control.theme
        if theme != null: break
        control = control.get_parent()
    return theme

Note, that'll return either the first defined theme found, or null if it runs into a node that doesn't have a theme property.

by (10,914 points)

Thank you for the suggestion. Although your solution will undoubtedly work, I was kinda hoping there was a function for this, seeing as most of the Editor itself uses Themes in this way.
Who knows, it might make a good feature proposal.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.