Search code examples
pythonuser-interfacemayamel

Using variables in a string - specifically stylesheets in Python/Maya


This is a follow up to a question I had on changing colors in the Maya UI. I was lucky enough to get some great info, and continuing the exercise I was trying to add a variable for the RGB float value in the stylesheet.

I've been learning a bunch and realized that I was essentially trying to use an int or float in a string, so I made a random list of float variables I thought I could use for "color" property instead of "rgb". So far any attempt at concatenating the data with a .format I could not seem to make it work. Still Googling for answers, but thought I'd ask if someone could point me in right direction.

gMainWindow = maya.mel.eval('$tmpVar=$gMainWindow')
import random
import shiboken2
from maya import cmds
from maya import OpenMayaUI
from PySide2 import QtWidgets
from PySide2.QtCore import *
from PySide2.QtWidgets import *

def clamp(num, min_value, max_value):
   return max(min(num, max_value), min_value)

r = random.randrange(0,255)
g = random.randrange(0,255)
b = random.randrange(0,255)
rgb = [r,g,b]

colorRGB = ['Red', 'White', 'Blue']
color2= random.choice(colorRGB)

window = cmds.window(gMainWindow, edit=True, backgroundColor=(r,g,b))

panels = cmds.getPanel(scriptType="scriptEditorPanel")  # Get all script editor panel names.

if panels:  # Make sure one actually exists!
    script_editor_ptr = OpenMayaUI.MQtUtil.findControl(panels[0])  # Grab its pointer with its internal name.
    script_editor = shiboken2.wrapInstance(long(script_editor_ptr), QtWidgets.QWidget)  # Convert pointer to a QtWidgets.QWidget
    editor_win = script_editor.parent().parent().parent().parent()  # Not very pretty but found that this was the best object to color with. Needed to traverse up its parents.
    editor_win.setObjectName("scriptEditorFramePanel")  # This object originally had no internal name, so let's set one.
    #editor_win.setStyleSheet("scriptEditorFramePanel {border: 13px solid rgb(155,155,155);}")  # Set its styleSheet with its internal name so that it doesn't effect any of its children.
    editor_win.setStyleSheet("scriptEditorFramePanel {border: 13px solid color{0}}".format(color2) 

I am specifically trying to change this line:

editor_win.setStyleSheet("scriptEditorFramePanel {border: 13px solid rgb(155,155,155);}") 

I can manually assign colors either by changing the RGB values, or setting a "color: (color name)", but I thought it would be interesting to see how I could use variables in a string like this.

Thanks! Alex


Solution

  • The problem your having is due to the literal curly braces in the string that are getting confused with the ones that surround the placeholder value. You need to replace them with two braces in a row to tell python to treat them as a literal brace:

     editor_win.setStyleSheet("scriptEditorFramePanel {{border: 13px solid color{0}}}".format(color2)