How to save changes in a custom window?(python Maya)

How to save changes in a custom window?(python Maya)

Hans_Redman
Advocate Advocate
3,367 Views
20 Replies
Message 1 of 21

How to save changes in a custom window?(python Maya)

Hans_Redman
Advocate
Advocate

How to save changes in a custom window?

I have a custom window that allows people to change the texture on the mesh. The problem is when I close the window and reopen it again, it won't save the changes (it will back to the default options). It can be confused sometimes. Does anyone know how to fix that by use python?
Many thanks

0 Likes
Accepted solutions (2)
3,368 Views
20 Replies
Replies (20)
Message 2 of 21

e_honda
Enthusiast
Enthusiast

Hi,

You can use cmds.optionVar.

https://help.autodesk.com/cloudhelp/2022/ENU/Maya-Tech-Docs/CommandsPython/optionVar.html

 

You can trigger a save command when window is closed and query command when window is opened.

Hope it helps.

0 Likes
Message 3 of 21

Hans_Redman
Advocate
Advocate

Hi e_honda,
Thank you for answer my question, I'm pretty new to python, can you give me an example how that will works please?
Many thanks

Message 4 of 21

e_honda
Enthusiast
Enthusiast
Accepted solution

Hi,

 

The code below is a simple example of creating, loading, updating and deleting variables that persists in Maya's preferences.

You can use something like this to save your preferences when you close your window and load preferences when you open your window.

Hope it helps.

 

from maya import cmds


def save_settings(key_name, value):
    """
    save current value with optionVar
    In this case, it forces a string value.
    Args: 
        key_name (str): name of the preference. should be unique.
        value (any): value. anything will be converted to string
    """
    cmds.optionVar(stringValue=(key_name, str(value)))
    print('Save %s' % key_name)

def load_settings(key_name, default_value=''):
    """
    load value from saved optionVar
    Args:
        key_name (str): name of the preference.
        default_value (any): default value used when setting is not saved yet
    """
    result = default_value
    if not cmds.optionVar(exists=key_name):
        return result
    result = cmds.optionVar(query=key_name)
    print('Load %s' % key_name)
    return result

# ---
# test
my_pref_name = '_TEST_KEY_VAL'
# delete old values
cmds.optionVar(remove=my_pref_name)
# load value. it was deleted in the line above, so it should return the default value
print(load_settings(my_pref_name, 'default_value'))
# create value
save_settings(my_pref_name, 'saved_value')
# shold return saved_value
print(load_settings(my_pref_name, 'default_value'))
# update value
save_settings(my_pref_name, 'updated_value')
# shold return updated_value
print(load_settings(my_pref_name, 'default_value'))

 

 

Message 5 of 21

Hans_Redman
Advocate
Advocate

Hi Honda, I have tried to add your code to my script but it didn't work(To be honest, I understand your code, I just don't know how to use it... How to link them together), can you have a look at my code for me please? 
I have 3 Radio Buttons in my script I just want to save the changes after I close the window. 

import maya.cmds as cmds

TEX = "10"
my_pref_name = '_TEST_KEY_VAL'
def windowUI(*args):
    ...

    #High
    cmds.radioButton("high", w=220, l="High", 
     onc="cmds.button('apply_button', e=True, en=True); TEX ='30'")
     
    #Medium
    cmds.radioButton("medium", w=220, l="Medium",
     onc="cmds.button('apply_button', e=True, en=True); TEX ='20'")
     
    #Low (Default)
    z = cmds.radioButton("low", w=220, l="Low", sl=True,
     onc="cmds.button('apply_button', e=True, en=True); TEX ='10'")
     cmds.setParent("..")

    #Apply button
    cmds.button("apply_button", label="Apply", w=360, c=xxxx, enable=False)

    cmds.setParent("..")
    cmds.separator(h=10, st='in')

    ...

    #Save Setting
def save_settings(key_name, value):

    cmds.optionVar(stringValue=(key_name, str(value)))
    print('Save %s' % key_name)

#Load Setting
def load_settings(key_name, default_value=''):

    result = default_value
    if not cmds.optionVar(exists=key_name):
        return result
    result = cmds.optionVar(query=key_name)
    print('Load %s' % key_name)
    return result

 

0 Likes
Message 6 of 21

Hans_Redman
Advocate
Advocate
Many thanks!
0 Likes
Message 7 of 21

e_honda
Enthusiast
Enthusiast
Hi,

Can you share more details about the problem?
It seems that you're trying to do something like below(correct me if I'm missing something):
1. create a window
2. populate the gui
3. load preferences (and change gui values)
4. show gui
5. when closing the window, save preferences

I'm guessing that you cannot find a way to save preferences on close. (In other words, step 5)
If so, the following thread is exactly about how to do it.
https://forums.autodesk.com/t5/maya-programming/is-there-a-way-to-define-callback-when-a-script-wind...

Hope it helps.
Message 8 of 21

Hans_Redman
Advocate
Advocate
Hi,

Pretty much like that(step 5). I'm just trying to save the value. As I said before when I close the window the value won't save at the moment.

For example:
1. I run the code, open the window, the 'low' radio button will be selected because it has the default value(sl=True).
2. I change the value from 'low' to 'high' then close the window.
3. Run the code again, open the window, it will back to 'low' again(it should be 'high').
So I want it to be 'high' when I reopen the window. (Save changes)

Overall, I'm just trying to find a way to save the values/changes.

I have looked at the link, same problem/needs. But the code seems MEL isn't? I will give it a try tomorrow.

Thank you for your help!
0 Likes
Message 9 of 21

Hans_Redman
Advocate
Advocate
Hi,
thank you for share the link with me! I have looked at it and I don't think the link you send to me will works.
It look like a MEL code and also it seems need a 'myGlobalProc()' function which I don't know what is it, the person didn't share that part.
Thanks again for your help!
0 Likes
Message 10 of 21

e_honda
Enthusiast
Enthusiast

Hi,

 

Maya's MEL API is similar to Python's Commands API (they're different, but almost the same).

 

Anyway, the example below shows you how to call a function when a window is closed in MEL and Python.

MEL

global proc tempProc(){
    print "MEL window closed";
}

string $window = `window -title "MELWindow" -widthHeight 300 50 -closeCommand ("tempProc();")`;
showWindow $window;

Python

from maya import cmds

def tempProc():
    print "Python window closed";


window = cmds.window(title="PythonWindow", widthHeight=(300,50), closeCommand=tempProc)
cmds.showWindow(window)

 

Many script examples out there are in Python or MEL, not both.

Maya's documentation is a good start point to learn them, because it has examples written in both languages.

https://help.autodesk.com/cloudhelp/2015/ENU/Maya-Tech-Docs/Commands/window.html

https://help.autodesk.com/cloudhelp/2015/ENU/Maya-Tech-Docs/CommandsPython/window.html

 

It'll be easier to you if you could understand their syntax and be able to read both of them.

 

Hope it Helps.

Message 11 of 21

Hans_Redman
Advocate
Advocate
Hi man,

Thank your reply. 😄
I have fixed the problem now. It's "closeCommand" + "optionVar" + if & elif loop to fix the problem.
Much appreciated!!

0 Likes
Message 12 of 21

Hans_Redman
Advocate
Advocate
Got a new problem, hahaha. They value won't reset after open a new scene.
If I select 'High' button and close the scene then open a new scene, the 'High' button will still be selected. (Because it has been saved in the Maya memory) At lest, the saving and loading function works.
Overall it worked perfectly fine.

Thank you so much for you help!!
0 Likes
Message 13 of 21

malcolm_341
Collaborator
Collaborator

optionVar saves the value to an external Maya preferences file so it will persist after Maya restart. If you want the value to reset you need to either add a reset button to your window to clear out the optionVar when the user wants, or you could run a script job that clears the value out each time a new scene is created. If you want the tool to reset after you close Maya don't use optionVar and instead just make a global variable for the state of the radio button and that will remember the button position during your current Maya session only.

0 Likes
Message 14 of 21

Hans_Redman
Advocate
Advocate
I didn't know the optionVar does that, I just want a function that can save the values. 😛
0 Likes
Message 15 of 21

Hans_Redman
Advocate
Advocate

Is that possible it add a function/script to clears the value when close the Maya? Or is there another command I can use to save value?
Cheers 

0 Likes
Message 16 of 21

malcolm_341
Collaborator
Collaborator
Accepted solution

Sure you have a bunch choices, if you use a global variable instead of an option var it will automatically clear the global variable when Maya closes.

If you want to also clear the global variable when you open a new scene you can start a scriptJob -event "SceneOpened" when your toolbox opens and update the variable and UI each time a scene is opened.

Message 17 of 21

Hans_Redman
Advocate
Advocate
Sweet as, Do you might to give me an example please?
0 Likes
Message 18 of 21

Hans_Redman
Advocate
Advocate

If someone can help me with the save problem that would be great. 
Cheers

0 Likes
Message 19 of 21

malcolm_341
Collaborator
Collaborator

This is one way to do it, it might not be the best way though. This is the first radio control I've created, I usually use checkboxes, but this works.

global proc textureOne()
{
	//Put your code here
	
	global int $g_radioRemember;
	$g_radioRemember = 1;
	
	print ("Radio button ONE\n");
}

global proc textureTwo()
{
	//Put your code here
	
	global int $g_radioRemember;
	$g_radioRemember = 2;
	
	print ("Radio button TWO\n");
}


global proc myWindow_launchWindow()
{
	if (`window -exists myWindow_windowName`)
	{
		deleteUI myWindow_windowName;
	}
	
	global int $g_radioRemember;
	window -title "My Window" -sizeable true -resizeToFitChildren true myWindow_windowName;
	columnLayout -adjustableColumn true;
	setParent ..;
	rowColumnLayout -numberOfRows 1;
	radioCollection myWindow_collectionName;
	if ($g_radioRemember == 1)
	{
		radioButton -label "Texture One" -onCommand "textureOne;" -select myWindow_buttonNameOne;
		radioButton -label "Texture Two" -onCommand "textureTwo;" myWindow_buttonNameTwo;	
	}
	else if ($g_radioRemember == 2)
	{
		radioButton -label "Texture One" -onCommand "textureOne;" myWindow_buttonNameOne;
		radioButton -label "Texture Two" -onCommand "textureTwo;" -select myWindow_buttonNameTwo;	
	}
	else
	{
		radioButton -label "Texture One" -onCommand "textureOne;" myWindow_buttonNameOne;
		radioButton -label "Texture Two" -onCommand "textureTwo;" myWindow_buttonNameTwo;	
	}
	
	showWindow;
}
myWindow_launchWindow();

Message 20 of 21

Hans_Redman
Advocate
Advocate
Is that a MEL script? I will have a look now.
Thank you for your help man!!!
0 Likes