Search code examples
pythonmaya

Selecting parameters in mayagui in python


I have to create a GUI in maya python wherein I have to use Sql query to get projectname,os,projectid , path . For example in my code if Projectname selected is "Abc" then os,projectid and path should be selected as per the selected projectname. how to do this??

I got the projectname but i cannot get other parameters

import os,mysql.connector as mc , platform 
cmds.window(title='Test Window')
name = []
id = []  
Os = []
path = []
wpath = []
# Query for getting various projects from db 
cursor = db.cursor()
#selecting projectname
ans = cursor.fetchall()
cursor.close()
def projid(name):
  #selecting project id
   pid = cursor.fetchone()
   print "out"
   print pid



 def Getprojid(z):
   global pname
    pname =  cmds.optionMenu(z , query=True,value = True)


for ans1 in ans:
   name .append(ans1[0])

cmds.columnLayout()
polygonSelectMenu = cmds.optionMenu(w = 250, h = 30, label = "Project 
Selection:")
for proj in name:
   cmds.menuItem(label = proj)



cmds.button(label='click me Select project ', 
command='printTxtField(polygonSelectMenu)')

cmds.showWindow()

Solution

  • Since you are new to Python Maya Gui, you have to take care of few things while writing tools which involved ui interaction.

    • Keep your UI module and Core module(The core functionality part or the data layer) separate.
    • If you have any Database association, keep the DB module separate, which should ideally read, write or update the database.
    • If possible you can also keep an interaction layer or module for integrating the core and ui module along with db layer.

    There can be more granular or organized designs, but as for starting this will help you to get the things done. Given below is an example from your requirement.

    Here I am assuming your project and its relevant details are coming from database or any other resources.

    #=========================================================================#
    # db code:
    #=========================================================================#
    
    # This module can have your own implementation. I am just writing some example code.
    
    def get_projects_data(*args, **kwargs):
        """ This should return all the records of the project table from your db.
        For filters you can pass them through kwargs.
        """
        return [{'id': 1021, 'name': 'Abc', 'os': 'some os', 'path': 'some path'},
                {'id': 1022, 'name': 'Def', 'os': 'some other os', 'path': 'some other path'}]
    
    
    #=========================================================================#
    # Ui Code:
    #=========================================================================#
    
    import maya.cmds as cmds
    
    class ProjectUI(object):
        _name = 'ProjectManager'
        _title = 'Project Manager'
    
    
        def __init__(self, project_data=None):
            self.project_data = project_data
            self.win = None
    
            # Create the UI
            self.create_ui()
    
            # Try to populate the projects
            self.populate_projects()
    
            # Force update the details for first time
            self.update_project_details()
    
        def create_ui(self):
            """This will create required UI components
            """
            # First check if the ui exists, then close it
            self.close()
    
            # Now thw create the window
            self.win = cmds.window(self.name, title=self.title)
            # Creat a column layout with adjustable True and row spacing to 5
            cmds.columnLayout(adj=True, rs=5)
    
            # Create project option menu and add a change commang to trigger while
            # you chnage the projects from the option menu.
            self.project_om = cmds.optionMenu(
                label='Projects', ChangeCommand=self.update_project_details)
    
            # Create required text fields
            self.project_id_tf = cmds.textFieldGrp(label='Id', editable=False)     
            self.project_path_tf = cmds.textFieldGrp(label='Path', editable=False)
            self.project_os_tf = cmds.textFieldGrp(label='OS', editable=False)
    
    
        def populate_projects(self):
            """This should populate all the available projects in poject option menu.
            """
            # First check if we have any project data in hand. If not then we should 
            # exit right away.
            if not self.project_data:
                print('No project data found for populatin projects')
                retturn
    
            for data in project_data:
                prject = data.get('name')
                menuItem(label=project, parent=self.project_om)
    
        def update_project_details(self, project=''):
            """This should update all other project details in UI and must me
            triggered while changing projects from poject option menu.
            """
            if not self.project_data:
                retturn
    
            if not project:
                project = cmds.optionMenu(self.project_om, q=True, value=True)
    
            project_details = None
            for data in self.project_data:
                if project == data.get('name'):
                    project_details = data
                    break
    
            if not project_details:
                print('No project details found for %s' % project)
                return
    
            proj_id = project_details.get('id')
            proj_path = project_details.get('path')
            proj_os = project_details.get('os')
    
            cmds.textFieldGrp(self.project_id_tf, e=True, text='%s' % proj_id)
            cmds.textFieldGrp(self.project_path_tf, e=True, text=proj_path)
            cmds.textFieldGrp(self.project_os_tf, e=True, text=proj_os)
    
        def show(self):
            """Just show the UI if its created ever.
            """
            if self.win:
                cmds.showWindow(self.win)
    
        def close(self):
            """For deleting the UI if exists
            """
            if cmds.window(self._name, query=True, exists=True):
                cmds.deleteUi(self.name, window=True)
    
    #=========================================================================#
    # Integration Code:
    #=========================================================================# 
    
    def main():
        # First fetch the data
        data = get_projects_data()
    
        if not data:
            print('No project data fetched.')
            return
    
        win = ProjectUI(project_data=data)
        win.show()
    
        # Return the win just if you want an pointer to same
        return win
    
    # Now just call the main method, whenever required
    main()
    

    The above code snippet is just an example. This is not tested inside maya. But I hope this will give you a starting point. Again if are not familiar with classes, you can do the same thing procedural way, by passing args. I will highly suggest PySide or PyQt along with PyMel for robust and efficient Ui Tools.