碧血红天的HomePage

Maya插件教程 — 5.3 快速选择工具案例

这里介绍一个制作一个属于自己的快速选择工具。我们可以事先编辑快速选择的规则,然后下次相同规则的模型进来,能够快速批量选择需要的对象,比如控制器等。我们在为绑定角色制作动画的时候,一个人物模型存在大量的控制器。动画师有时候想一次性选中全部手指的控制器或者整个手臂的控制器。这个时候有个快速批量选择的工具,那动画师的工作效率就会提高很多。

这里是我这制作的界面,选择模式是一个下拉列表,不同的模式里面可以添加不同的选择组。因为可能不同的绑定规则,控制器命名方式是不一样的。所以我们添加一个模式的选择。

模式我们可以添加,每一个模式我们会把描述信息写入一个文件,这样就实现了我们的保存,下次打开的时候能够直接把自己添加的模式和选择组自动导入进来。同时我们也支持把现有的模式进行修改,然后把修改的内容会写进入配置文件中。这里的配置文件使用的是json,因为能Python和Json能够很方便的快速互转,这是我们的首选。

5.3.1 Json文件结构

{
  "CurrentMode": "Adv", 
  "ModeData": [
    {
      "list": [
        {
          "button": "\u5de6\u624b\u81c2", 
          "rule": [
            "FKShoulder_L", 
            "FKElbow_L", 
            "FKWrist_L"
          ]
        }, 
        {
          "button": "\u53f3\u624b\u63a7\u5236\u5668", 
          "rule": [
            "FKPinkyFinger1_R", 
          ]
        }
      ], 
      "name": "Adv"
    }
  ]
}

上面是我的存储文件结构,这个根据自己的需求和习惯自己设计即可。这里我来解释一下我为什么这样设计。

CurrentMode:这是当前选中的模式。因为我们下次打开此界面的时候,能够优先选中我们上次关闭时的选择。
ModeData:这是一个数组,每个数组对象是一个模式信息对象。
list:存放我们选择组的按钮信息,里面包括按钮的名字,按钮要选择的对象名字。
button:按钮的名字。
rule:需要选择的对象名字。
name:模式的名字。

5.3.2 解析配置文件

现在我们解析上面的配置文件,首先读取文件数据,把读取的字符串通过json库解析成Python对象。然后根据里面的信息初始化我们的模式Combox控件和按钮组。

    def initMode(self):
        self.ui.modeModifyBtn.setEnabled(False)
        curPath = self.GetCurrentDir()
        ruleFile = curPath + '/rule.json'
        if not os.path.exists(ruleFile):
            return
        with open(ruleFile,'r') as inFile:
            data = json.load(inFile)
            self.Data = data
        self.curtName = self.Data['CurrentMode']
        self.initModeComBox()
        self.refreshButtons()
    def initModeComBox(self):
        if self.Data == None:
            return
        self.ui.modeCombox.clear()
        for k in self.Data['ModeData']:
            name = k['name']
            if self.ui.modeCombox.findText(name) < 0:
                self.ui.modeCombox.addItem(name)
        self.ui.modeCombox.setCurrentText(self.curtName)
        if self.curtName == '':
            self.curtName = self.ui.modeCombox.currentText()
        if self.ui.modeCombox.currentText() != '':
            self.ui.modeModifyBtn.setEnabled(True)
        else:
            self.ui.modeModifyBtn.setEnabled(False)
def clearButtons(self):
        for k in self.buttons:
            self.ui.gridLayout.removeWidget(k)
            k.setParent(None)
        self.buttons = []
    
def refreshButtons(self):
        self.clearButtons()
        if self.Data == None:
            return
        item = self.findItem(self.Data,self.curtName)
        if not item:
            return
        row = 0
        col = 0
        mo = 2

        for n in item['list']:
            button = QuickSelectRuleButton.QuickSelectRuleButton()
            button.setRule(n['button'],n['rule'])
            self.ui.gridLayout.addWidget(button,row,col % mo)
            self.buttons.append(button)
            col += 1
            if col == mo:
                row += 1
                col = 0

这上面的代码都很简单,就是读取配置数据,然后动态创建对应的控件和还原控件中的数据。这里我们实现了一个自己的按钮QuickSelectRuleButton,这样我们方便响应自己的响应函数。

5.3.3 自定义控件

有时候为了方便,我们会实现一些自定义控件。比如我们这里想扩展一下我们的QPushButton,这样我们就能自定一些属性进去,然后方便我们操作。

# QuickSelectRuleButton.py
from PySide2 import QtWidgets, QtCore, QtGui
from PySide2.QtCore import Qt
import pymel.core as pm

class QuickSelectRuleButton(QtWidgets.QPushButton):
    def __init__(self):
        super(QuickSelectRuleButton, self).__init__()
        self.rule = []
        self.clicked.connect(self.onClick)

    def setRule(self,name,rule):
        self.rule = rule
        self.setText(name)

    def checkMatch(self,nodeName):
        for k in self.rule:
            if nodeName.endswith(k):
                return True
        return False

    def onClick(self):
        nodes = pm.ls()
        for k in nodes:
            if self.checkMatch(k.name()):
                pm.select(k.name(),add=1)

我们自定义的按钮,我们可以把选择规则设置进来,点击的响应就自动完成了,没必要我们使用QPushButton原生的按钮,每个按钮再单独设置点击响应。这里我们使用的是继承QPushButton来实现功能的扩展。

5.3.4 模式创建

上图是我们创建模式的一个窗口面板截图。我们有设置模板的名字,然后+号按钮是添加一个按钮,我们知道一个按钮代表一到多个的选择,所以我们需要创建一个空间,里面能设置按钮的名字和按钮选择的对象名字。

    def onAdd(self):
        itemWidget = QuickSelectRuleItem.QuickSelectRuleItem()
        itemWidget.setDelCallBack(self.delItemCallBack)
        item = QtWidgets.QListWidgetItem(self.ui.modeListWidget)
        item.setSizeHint(QtCore.QSize(0, 123));
        self.ui.modeListWidget.addItem(item)
        self.ui.modeListWidget.setItemWidget(item,itemWidget)
        self.itemList[itemWidget] = item

这里也很简单,我们需要知道怎么提取我们当前选中的对象的名字:

    def onSel(self):
        nodes = pm.selected()
        for n in nodes:
            name = n.name()
            ix = name.rfind(':')
            if ix > -1:
                name = name[ix+1:]
            self.ui.ruleNodesText.append(name)

我们使用rfind找到最后一个冒号,为了是把我们名字上的命名空间去掉。我们在选择的时候是不管命名空间的。

5.3.4 写配置文件

当我们点击确定按钮的时候,我们要把当前的内容保存出去,也就是把我们视图数据存储出去。上面已经介绍了我们配置文件的结构,我们构建出这样的对象即可。

def onOk(self):
        curPath = self.GetCurrentDir()
        ruleFile = curPath + '/rule.json'
        data = {}
        if os.path.exists(ruleFile):
            with open(ruleFile,'r') as inFile:
                data = json.load(inFile)
                inFile.close()
        else:
            data['CurrentMode'] = ''
            data['ModeData'] = []
        ruleName = self.ui.modeNameEdit.text()
        if ruleName == '':
            QtWidgets.QMessageBox.warning(self,'warning','需要设置名字',QtWidgets.QMessageBox.Ok)
            return
        if len(self.itemList) == 0:
            QtWidgets.QMessageBox.warning(self, 'warning', '需要至少选择一个对象', QtWidgets.QMessageBox.Ok)
            return
        if self.checkSame(data,ruleName):
            QtWidgets.QMessageBox.warning(self, 'warning', '名字重复,请重新设置', QtWidgets.QMessageBox.Ok)
            return
        item = {}
        item['name'] = ruleName
        item['list'] = []
        for t in self.itemList:
            ruleName = t.getRuleName()
            nodeNames = t.getNodeNames()
            if ruleName == '' or len(nodeNames) == '':
                continue
            item['list'].append({'button':ruleName,'rule':nodeNames})

        data['ModeData'].append(item)
        jsonStr = json.dumps(data, indent=2, sort_keys=True)
        with open(ruleFile,'w') as outFile:
            outFile.write(jsonStr)
            outFile.close()
        if self.okCallBack:
            self.okCallBack()
        self.close()

好了,这个里面的新知识点很少,都是前面介绍的综合使用。下面附上完整的代码:

150 评论

  1. Having read this I thought it was extremely enlightening. I appreciate you finding the time and energy to put this article together. I once again find myself spending a lot of time both reading and commenting. But so what, it was still worthwhile!

  2. Oh my goodness! Impressive article dude! Thank you, However I am experiencing difficulties with your RSS. I donít know the reason why I can’t subscribe to it. Is there anybody else getting the same RSS issues? Anyone who knows the answer can you kindly respond? Thanx!!

  3. This is a topic which is close to my heart… Best wishes! Where are your contact details though?

  4. This is a topic that’s near to my heart… Thank you! Where are your contact details though?

  5. Hi there! I simply wish to give you a huge thumbs up for the great information you have right here on this post. I am coming back to your blog for more soon.

  6. An interesting discussion is worth comment. I do believe that you need to publish more on this issue, it might not be a taboo matter but typically folks don’t talk about such subjects. To the next! Kind regards!!

  7. I could not resist commenting. Well written!

  8. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a little bit, but other than that, this is great blog. A fantastic read. I’ll certainly be back.

  9. Pretty! This was an incredibly wonderful post. Thank you for supplying this info.

  10. After checking out a number of the blog posts on your web site, I honestly appreciate your way of writing a blog. I book-marked it to my bookmark webpage list and will be checking back in the near future. Take a look at my website as well and tell me your opinion.

  11. 16 Clark TJ, Mann CH, Shah N, Song F, Khan KS, Gupta JK stromectol cena

  12. can i buy priligy over the counter They also suggest that an LTT approach could be developed for any small, lipophilic molecule with good dermal permeation, thus greatly expanding the menu of drugs that could be tested for breast cancer prevention

  13. will nolvadex raise testosterone meeting By Josh Mitchell Staff reporter The City Council is still considering raising rates for water, sewer and garbage to meet budget shortfalls in the fiscal year that begins July 1

  14. Oh my goodness! Impressive article dude! Thank you so much, However I am having problems with your RSS. I donít know why I am unable to subscribe to it. Is there anyone else getting identical RSS problems? Anyone that knows the solution will you kindly respond? Thanks!!

  15. Hi, I do think this is an excellent web site. I stumbledupon it 😉 I may return yet again since I bookmarked it. Money and freedom is the best way to change, may you be rich and continue to help other people.

  16. You are my inspiration , I own few web logs and sometimes run out from to post .

  17. Wheatley KE, Nogueira LM, Perkins SN, Hursting SD Differential effects of calorie restriction and exercise on the adipose transcriptome in diet induced obese mice zinc and zithromax hey everyone, I am so glad I found this website

  18. The next time I read a blog, Hopefully it does not disappoint me just as much as this one. After all, I know it was my choice to read through, however I truly thought you would have something useful to talk about. All I hear is a bunch of crying about something you could possibly fix if you weren’t too busy looking for attention.

  19. Itís hard to come by knowledgeable people about this subject, but you seem like you know what youíre talking about! Thanks

  20. Pretty! This was an incredibly wonderful article. Many thanks for providing this information.

  21. The interaction between drugs and gut microbe composition is important for understanding drug mechanisms and the development of certain drug side effects 1, 2 propecia online australia

  22. An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

  23. Only wanna remark that you have a very decent internet site, I love the pattern it actually stands out.

  24. hi!,I like your writing so much! proportion we keep in touch more about your post on AOL? I require an expert on this space to resolve my problem. May be that is you! Taking a look forward to see you.

  25. I?¦ve been exploring for a little for any high-quality articles or weblog posts in this kind of house . Exploring in Yahoo I at last stumbled upon this site. Reading this info So i?¦m glad to exhibit that I have a very excellent uncanny feeling I came upon just what I needed. I most unquestionably will make certain to do not put out of your mind this site and provides it a glance on a continuing basis.

  26. It’s in point of fact a great and helpful piece of information. I’m happy that you simply shared this helpful info with us. Please stay us informed like this. Thank you for sharing.

  27. Excellent blog here! Also your web site loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  28. Reach your goals, obtain even more done and also enhance your life!

  29. Discover the very best behaviors of effective people.

  30. You may find that you are doing every little thing faster, much better and also much more efficiently than ever in your life!

  31. Amazingness is a productivity booster that will certainly change your life for the better!

  32. Begin living your finest life now with the phenomenal!

  33. Achieve every one of your most important things faster and also easier!

  34. You are entitled to the best of every little thing in life. And this product can assist you arrive!

  35. Amazingness can help you be more effective, focused as well as live a healthier life!

  36. Extraordinary is a innovative technique for getting more done daily.

  37. Have a good time and obtain things made with the most fantastic device!

  38. You ‘d be in awe of just how good this goes to what it does!

  39. The Incredible method to transform your life for the better!

  40. Sign up currently and get going on your trip today!

  41. Incredible is an all-in-one life management tool that will certainly aid you stay on top of your to-dos, goals, as well as schedule.

  42. Find out exactly how amazingness sustains your service development with the remarkable power it holds.

  43. Every little thing you need is right below!

  44. Begin feeling fantastic today by living the life that you’ve constantly wanted!

  45. End up being a master in everything with this!

  46. Amazing is the one stop look for whatever performance.

  47. Remarkable is a life changing tool that will certainly aid you be more effective as well as improve outcomes.

  48. Be the best at everything you do!

  49. Incredible will provide you a lot of outstanding possibilities.

  50. Amazing advantages for you, friends and family that keep giving.

  51. The Amazingness life performance system gives you more time and energy to do what you love.

  52. This simply may be the life-changing product you have actually been waiting on.

  53. Amazingness is a performance booster that will certainly transform your life right!

  54. Have a look at just how this tool can alter your life right!

  55. Get one year free plus up to 40 off your first registration!

  56. I simply wished to appreciate you once more. I’m not certain the things I would have used in the absence of the tricks shared by you relating to such problem. It previously was a real alarming crisis in my view, nevertheless being able to view the expert strategy you processed that forced me to jump for happiness. I’m just grateful for the work and then wish you are aware of a powerful job that you’re doing educating other individuals through the use of your web site. More than likely you’ve never encountered any of us.

  57. Phenomenal is the best efficiency device for busy individuals who want to get more done in much less time.

  58. Check out exactly how this set device can change your life right!

  59. Discover exactly how to maintain your home tidy as well as tidy in 30 minutes!

  60. Be the very best at every little thing you do!

  61. The Incredible means to change your life for the better!

  62. Unbelievable advantages for you, friends and family that continue giving.

  63. Obtain all you need and also much more with this!

  64. Same thing with that if you put in a little in today, a little in tomorrow, you know, gradually, step by step, you ll get what you re looking for without INAUDIBLE towards just messing yourself up 10mg nolvadex during cycle

  65. None of the patients with renal amyloidosis had any preexisting or coexisting illness doxycycline coronavirus

  66. Incredible is the performance application that will alter your life.

  67. This is something that every family and also organization requirements.

  68. Be better, much more innovative, and extra efficient!

  69. It’s that time once again to obtain every little thing performed in a really short time period.

  70. I thought it was over and was looking forward to trying again most reliable site to buy clomid clomid ondansetron 8mg odt Non oil re exports from the city state, for instance, grew14

发表评论