Load a texture to TextureButton with Theme?

Godot 4.2.2

Question

I want to load textures for TextureButton with Theme set in code.

I have paths to files

@export_group('Buttons')
@export_subgroup('Textures')
@export_file('*.png', '.jpg') var button_texture_normal := "res://addons/dialogic_additions/DefaultLayoutParts/Layer_TextureChoice/button_textures/normal.png"
@export_file('*.png', '.jpg') var button_texture_hovered := "res://addons/dialogic_additions/DefaultLayoutParts/Layer_TextureChoice/button_textures/hover.png"
@export_file('*.png', '.jpg') var button_texture_pressed := "res://addons/dialogic_additions/DefaultLayoutParts/Layer_TextureChoice/button_textures/pressed.png"
@export_file('*.png', '.jpg') var button_texture_disabled := ""
@export_file('*.png', '.jpg') var button_texture_focused := ""

Overrides stored in theme variable and then applied to layer’s root node.
But I don’t know how to load textures correctly.
I tried StyleBoxTexture but it didn’t work.

    var theme: Theme = Theme.new()
    if ResourceLoader.exists(button_texture_normal):
        var style_box: StyleBoxTexture = StyleBoxTexture.new()
        style_box.texture = load(button_texture_normal)
        theme.set_stylebox('texture_normal', 'TextureButton', style_box)
        theme.set_stylebox('texture_hover', 'TextureButton', style_box)
        theme.set_stylebox('texture_pressed', 'TextureButton', style_box)
        theme.set_stylebox('texture_disabled', 'TextureButton', style_box)
        theme.set_stylebox('texture_focus', 'TextureButton', style_box)

How to properly load texture to TextureButton with the Theme class?

1 Like

I had to use this, honestly, I’m not sure where in the documents it mentions this because someone showed it to me, but try it out.

var HB_active_tex = preload("res://UI/items/HBactiveSlot.png")
var HB_active_style : StyleBoxTexture = null

func _ready():
	HB_active_style = StyleBoxTexture.new()
	HB_active_style.texture = HB_active_tex

func refresh_style(active: bool):
	if active:
		set("theme_override_styles/panel", HB_active_style)
	else:
		set("theme_override_styles/panel", null)

That works for usual Button, but TextureButton can’t be themed as I discovered.

1 Like

@jomi
Eventually I did it without Theme, because if it applied to TextureButton it’s affecting only child nodes.

piece of code:

	if ResourceLoader.exists(button_texture_normal):
		#Choices containing TextureButtons
		for choice in $Choices.get_children():
			choice.texture_disabled = load(button_texture_normal)
			choice.texture_focused = load(button_texture_normal)
			choice.texture_hover = load(button_texture_normal)
			choice.texture_normal = load(button_texture_normal)
			choice.texture_pressed = load(button_texture_normal)
			choice.texture_click_mask = null

	if ResourceLoader.exists(button_texture_hovered):
		for choice in $Choices.get_children():
			choice.texture_hover = load(button_texture_hovered)
	
	#etc for every texture
1 Like