Search code examples
pythonpysidemaya

I can't get my GUI to load and recognize buttons using PySide


Here is the error I am getting, which I am really confused about. My UI file which I am loading has this button name and it matches. But for some reason it doesn't seem to recognize and load it. I just tried converting this code over to PySide (it was originally PyQt). Am I doing something wrong in translating it?

Error: AttributeError: file line 25: 'swapRefGUI' object has no attribute 'swapRefBtn' #

from PySide import QtCore, QtGui, QtUiTools
import maya.cmds as cmds

class swapRefGUI(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        loader = QtUiTools.QUiLoader()
        uifile = QtCore.QFile('C:\Scripts\swapRef.ui')
        uifile.open(QtCore.QFile.ReadOnly)
        ui = loader.load(uifile, parent)
        uifile.close()

        self.setFixedSize(400, 300)

        self.swapRefBtn.clicked.connect(self.swapRefBtn_clicked)
        self.closeBtn.clicked.connect(self.close)               

    def swapRefBtn_clicked(self):
        pass                          

if __name__ == "__main__": 
    #app = QApplication(sys.argv)
    app = QApplication.instance()
    if app is None:
        app = QApplication(sys.argv)    
    myGUI = swapRefGUI(None)
    myGUI.show()
    sys.exit(app.exec_())

Solution

  • Right now you are trying to access swapRefBtn through the class instance swapRefGUI, but you actually need to access it through the ui variable where you load. The 2nd argument of loader.load should also be self to display the qt gui in your window. There's also a few instances where you are trying to access objects from PySide like QDialog, when it should be QtGui.QDialog (because of the way you imported PySide module).

    Here's some code that worked with a ui file.

    from PySide import QtCore, QtGui, QtUiTools
    import maya.cmds as cmds
    
    class swapRefGUI(QtGui.QDialog):
        def __init__(self, parent=None):
            QtGui.QDialog.__init__(self, parent)
    
            loader = QtUiTools.QUiLoader()
            uifile = QtCore.QFile('C:\Scripts\swapRef.ui')
            uifile.open(QtCore.QFile.ReadOnly)
            self.ui = loader.load(uifile, self) # Qt objects are inside ui, so good idea to save the variable to the class, 2nd arg should refer to self
            uifile.close()
    
            self.setFixedSize(400, 300)
    
            self.ui.swapRefBtn.clicked.connect(self.swapRefBtn_clicked) # Need to access button through self.ui
            #self.ui.closeBtn.clicked.connect(self.close) # This needs to have an existing function in the class or it will crash when executing
    
        def swapRefBtn_clicked(self):
            print 'WORKS'  
    
    myGUI = swapRefGUI()
    myGUI.show()