PyHP3D
PyHP3D

Reputation: 88

How to get the Maya/Qt GUI component that is calling a function?

I am trying to figure out a way to somehow "get" the GUI component that is invoking a function. This way I can further consolidate my code into reusable parts for components that do similar tasks. I need a way to do this in Maya's GUI commands as well as Qt's. I guess what I'm looking for is a general python trick like the "init", "file", "main", etc. If there isn't a general python way to do it, any Maya/Qt specific tricks are welcome as well.

Here is some arbitrary pseudo code to better explain what I'm looking for:

field1 = floatSlider(changeCommand=myFunction)
field2 = colorSlider(changeCommand=myFunction)

def myFunction(*args):
    get the component that called this function

    if the component is a floatSlider
        get component's value
        do the rest of the stuff

    elif the component is a colorSlider
        get component's color
        do the rest of the stuff

Upvotes: 0

Views: 996

Answers (1)

Green Cell
Green Cell

Reputation: 4777

Expanding from Gombat's comment, here's an example of how to get a generic function to work with a slider and a spinBox control:

from PySide import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, parent = None):
        super(Window, self).__init__(parent)

        # Create a slider
        self.floatSlider = QtGui.QSlider()
        self.floatSlider.setObjectName('floatSlider')
        self.floatSlider.valueChanged.connect(self.myFunction)

        # Create a spinbox
        self.colorSpinBox = QtGui.QSpinBox()
        self.colorSpinBox.setObjectName('colorSlider')
        self.colorSpinBox.valueChanged.connect(self.myFunction)

        # Create widget's layout
        mainLayout = QtGui.QHBoxLayout()
        mainLayout.addWidget(self.floatSlider)
        mainLayout.addWidget(self.colorSpinBox)
        self.setLayout(mainLayout)

        # Resize widget and show it
        self.resize(300, 300)
        self.show()

    def myFunction(self):
        # Getting current control calling this function with self.sender()
        # Print out the control's internal name, its type, and its value
        print "{0}: type {1}, value {2}".format( self.sender().objectName(), type( self.sender() ), self.sender().value() )

win = Window()

I don't know what control you would want colorSlider (I don't think PySide has the same slider as the one in Maya, you may have to customize it or use a QColorDialog). But this should give you a rough idea of how to go about it.

Upvotes: 1

Related Questions