简体   繁体   中英

How do you set the directory in Maya with python? Currently using PyQt4 but open to any suggestions

I need to set the directory in Maya so that when I import a new file it will go to that directory I imported the last file from. It is for multiple scripts. I import files, run a script, then run a new script. I can't use string or reset my project folder. This is the only part of my scripts I can't get to work. Here is a list of my imports:

import maya.cmds as cmds
import sip
import maya.OpenMayaUI as apiUI
from PyQt4 import QtGui, QtCore
import os
import os.path
import maya.mel as mel

Here is the part that is giving me trouble (for simplicity I put an actual path). I am new too scripting in general. I know I am missing information, but I have no idea what. I have tired so many different things.

#Set file path
directory = QtGui.QFileDialog.setDirectory('C:\Users')

I get this error every time:

# TypeError: # arguments did not match any overloaded call:
#   QFileDialog.setDirectory(QString): first argument of unbound method must have type 'QFileDialog'
 QFileDialog.setDirectory(QDir): first argument of unbound method must have type 'QFileDialog'

I have even tried going simple with workspace. It prints correctly with no errors but when I go to file open it takes me back to where I saved last.

#Give file path
cmds.workspace(dir='C:\Users')
#Find file path
foo = cmds.workspace(q=True, dir=True)
print foo

Here is the script. It is a composite between myself and another person. It's function is to import mesh and auto project UVs. Which are then optimized by the artist. Then exported to save a separate version. The next part is importing the optimize mesh (import is required because the stages need to be able to work independently). I hope this makes more sense now.

import maya.cmds as cmds
import sip
import maya.OpenMayaUI as apiUI
from PyQt4 import QtGui, QtCore
import os
import os.path
import maya.mel as mel

class LPUnion(QtGui.QMainWindow):
    def __init__(self,
                 parent=getMayaMainWindow(),
                 uniqueHandle='ImportExport'):
        QtGui.QMainWindow.__init__(self, parent)
        self.setWindowTitle('Low Poly')
        self.setObjectName(uniqueHandle)
        self.init_ui()


    def init_ui(self):
        """
        Create the class vars and UI elements
        """
        print('setting window')
        central_widget = QtGui.QWidget()
        central_layout = QtGui.QGridLayout()

        central_widget.setLayout(central_layout)
        self.setCentralWidget(central_widget)

        self.setGeometry(300,300, 250, 150)

        lbt=QtGui.QLabel("Import low poly for automatic UV mapping")
        self.aBtn = QtGui.QPushButton("Import Low Poly")
        self.aBtn.clicked.connect(self.import_low_obj)        

        lbh=QtGui.QLabel("Resize UVs before exporting optimized")
        self.oBtn = QtGui.QPushButton("Export Optimized")
        self.oBtn.clicked.connect(self.export_opt_obj) 

        lbn=QtGui.QLabel("Import union for chunking")
        self.uBtn = QtGui.QPushButton("Import for Chunking")
        self.uBtn.clicked.connect(self.import_uni_obj)

        lbk=QtGui.QLabel("Export chunking")
        self.yBtn = QtGui.QPushButton("Export Chunks")
        self.yBtn.clicked.connect(self.export_chks)

        central_layout.addWidget(lbt)
        central_layout.addWidget(self.aBtn)
        central_layout.addWidget(lbh)
        central_layout.addWidget(self.oBtn)
        central_layout.addWidget(lbn)
        central_layout.addWidget(self.uBtn)
        central_layout.addWidget(lbk)
        central_layout.addWidget(self.yBtn)

        self.show()

#import for optimization
    def import_low_obj(self):
        """
        import a selected file
        """

        lpfiles = QtGui.QFileDialog.getOpenFileName(self, 'Import for Optimized')
        if lpfiles != None:
            n = str(lpfiles)
            print "name is {0}".format(n)
            #split up name to import other items
            self.root = n.replace(n.split('/')[-1:][0], "")
            print "root is {0}".format(self.root)

            #create new scene
            cmds.file(new=True, force=True)

            # import n
            self.objs = []
            for fn in [n]:
                cmds.file(fn, i=True)
                for o in cmds.ls(type="mesh"):
                    if not o in self.objs:
                        self.objs.append(o)

            #####set directory
            fileName = os.path.dirname(n)
            #####directory = QtGui.QFileDialog.setDirectory('path/to/dir')####

            print self.objs
            cmds.select(cl=True)
            #triangulate mesh
            for o in self.objs:
                cmds.polyTriangulate(o)
            cmds.select(cl=True)

            #automatic mapping of UVs
            cmds.select('mesh', r=True)
            cmds.hilite('mesh', r=True)
            cmds.selectMode(component=True)
            cmds.select('mesh.f[0:10000]', r=True)
            cmds.polyAutoProjection('mesh.f[0:10000]', lm = 1, cm=False, l = 2, sc = 1, o = 1, ps = 0.2, ws=False)



            QtGui.QMessageBox.information(None,
                                        "Uploaded",
                                        "Optimize Uvs before exporting.".format(self.intr)) 


#export optimized
    def export_opt_obj(self):
        """
        export the new mesh
        Q:\KITCHEN\mesh\Modo\ECO\113
        """

        #export two copies of obj
        cmds.select(cl=True)
        cmds.select('mesh')
        cmds.file(self.root+"mesh-lowpoly-optimize", force=True, es=True, op="groups=1;ptgroups=0;materials=0;smoothing=0;normals=0", typ="OBJexport")
        cmds.select(cl=True)
        cmds.select('mesh')
        cmds.file(self.root+"mesh-lowpoly", force=True, es=True, op="groups=1;ptgroups=0;materials=0;smoothing=0;normals=0", typ="OBJexport")

        QtGui.QMessageBox.information(None,
                                    "Saved",
                                    "Optimized mesh files have been saved.".format(self.intr)) 



#import for chunking
    def import_uni_obj(self):
        """
        import a selected file
        """



        unifiles = QtGui.QFileDialog.getOpenFileName(self, 'Import for Chunking')


        if unifiles != None:
            n = str(unifiles)
            print "name is {0}".format(n)
            #split up name
            self.root = n.replace(n.split('/')[-1:][0], "")
            print "root is {0}".format(self.root)

            #create new scene
            cmds.file(new=True, force=True)

            # import n
            self.objs = [] #add mesh to this list, LP mesh
            for fn in [n]:
                cmds.file(fn, i=True)
                for o in cmds.ls(type="mesh"):
                    if not o in self.objs:
                        self.objs.append(o)

            print self.objs

            cmds.select(cl=True)
            #triangulate mesh
            cmds.polyTriangulate('mesh')

            #create locator
            cmds.spaceLocator(p = [0, 0, 0])
            cmds.setAttr("locator1.tx", lock=True, channelBox=True)
            cmds.setAttr("locator1.ty", lock=True, channelBox=True)


            QtGui.QMessageBox.information(None,
                            "Great!",
                            "From side view move locator to cut position .".format(self.intr))



#export chunking
    def export_chks(self):

        import maya.cmds as cmds

        ###make chunks
        cmds.duplicate('mesh')
        cmds.duplicate('mesh')
        cmds.duplicate('mesh')

        #delete the right side
        leftChunks = ['mesh', 'mesh1']
        for n in leftChunks:
            cmds.select(n)
            cmds.polyCut(cutPlaneCenterX = 0 , cutPlaneRotate = [0, 90, 0], deleteFaces = True)

        #delete the left side
        rightChunks = ['mesh2', 'mesh3']
        for p in rightChunks:
            cmds.select(p)
            cmds.polyCut(cutPlaneCenterX = 0 , cutPlaneRotate = [0, -90, 0], deleteFaces = True)

        #get position of locator
        loPosition = cmds.pointPosition('locator1', w=True)

        #delete front
        backChunks = ['mesh', 'mesh2']
        for f in backChunks:
            cmds.select(f)
            cmds.polyCut(cutPlaneCenter = loPosition, cutPlaneRotate = [180, 0, 0], deleteFaces = True)
        cmds.rename('mesh', 'back_Left')
        cmds.rename('mesh2', 'back_Right')

        #delete back
        frontChunks = ['mesh1', 'mesh3']
        for t in frontChunks:
            cmds.select(t)
            cmds.polyCut(cutPlaneCenter = loPosition, cutPlaneRotate = [0, 0, 0], deleteFaces = True)
        cmds.rename('mesh1', 'front_Left')
        cmds.rename('mesh3', 'front_Right')

        #trianglate chunks
        triMesh = ['back_Left', 'back_Right', 'front_Left', 'front_Right']
        for s in triMesh:
            cmds.select(s)
            cmds.polyTriangulate(s)

        """
        export the new mesh

        """
        #save out chunks
        cmds.select(cl=True)
        cmds.select('back_Left')
        cmds.file(self.root+"mesh-back-left",force=True, es=True, op="groups=1;ptgroups=0;materials=0;smoothing=0;normals=0", typ="OBJexport")

        cmds.select(cl=True)
        cmds.select('back_Right')
        cmds.file(self.root+"mesh-back-right",force=True, es=True, op="groups=1;ptgroups=0;materials=0;smoothing=0;normals=0", typ="OBJexport")

        cmds.select(cl=True)
        cmds.select('front_Left')
        cmds.file(self.root+"mesh-front-left",force=True, es=True, op="groups=1;ptgroups=0;materials=0;smoothing=0;normals=0", typ="OBJexport")

        cmds.select(cl=True)
        cmds.select('front_Right')
        cmds.file(self.root+"mesh-front-right",force=True, es=True, op="groups=1;ptgroups=0;materials=0;smoothing=0;normals=0", typ="OBJexport")


LPUnion()

Here are my references:

http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html

http://zetcode.com/gui/pyqt4/dialogs/

And others.

Thanks in advance!!

This question could be clearer. If you're trying to force a dialog to open in a particular folder, QFileDialog.setDirectory is should be called from a QFileDialog object; if you have already created one you can call its setDirectory() method and it should work.

However you can do the same thing with

import maya.cmds as cmds
cmds.fileDialog2(dir='path/to/dir', dialogStyle=2, fileMode =4)

For the fileDialog2 command, see here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM