访问和修改 Maya 撤消队列

Access and modify Maya undo queues

有什么方法可以访问/编辑撤消队列?

我问的原因是,在我当前的工具中,我在我的重命名函数之一中创建了以下内容(您双击 QListWidgetItem,输入新名称,cmds.rename 将使用新的输入名称):

cmds.undoInfo(chunkName='renameChunk', openChunk=True)
# do cmds.rename operations
cmds.undoInfo(chunkName='renameChunk', closeChunk=True)

但是,如果我尝试执行撤消功能 (ctrl+z) 以恢复命名,我需要按几次组合键而不是预期的 1 次。在打印撤消队列时,我注意到有很多 'blank' 条目可能是多次撤消的原因。

...
# 39:  # 
# 40:  # 
# 41:  # 
# 42:  # 
# 43: renameChunk # 
# 44:  # 
# 45:  # 
# 46:  # 
# 47:  # 
# 48:  # 
# 49:  #

我将提供一个答案,因为你所做的有点冒险。现在你假设 cmds.undoInfo(chunkName='renameChunk', closeChunk=True) 将 运行,但如果发生错误 in-between 该行将永远不会执行,你将留下一个打开的撤消块。

一种更安全的方法是打开一个撤消块,然后将您的代码包装在 try finally 中。这样无论发生什么事你都可以确信块将在 finally 块中关闭:

cmds.undoInfo(chunkName='renameChunk', openChunk=True)
try:
    raise RuntimeError("Oops!")
finally:
    cmds.undoInfo(closeChunk=True)  # This will still execute.

或者,您可以更高级一些,创建自己的撤销 class 并利用它的 __enter____exit__ 特殊方法:

class UndoStack(object):

    def __init__(self, name="actionName"):
        self.name = name

    def __enter__(self):
        cmds.undoInfo(openChunk=True, chunkName=self.name, infinity=True)

    def __exit__(self, typ, val, tb):
        cmds.undoInfo(closeChunk=True)

with UndoStack("renameChunk"):  # Opens undo chunk.
    raise RunTimeError("Oops!")  # Fails
# At this point 'with' ends and will auto-close the undo chunk.

只要你这样做,你就不应该有所有这些空白的撤消调用(至少我没有!)。虽然尽量保持紧凑,但打开一个撤消块,完成工作,然后立即关闭它。避免做其他事情,比如管理你的图形用户界面之类的。