I am working on a mini GUI project , I am currently struggling to figure out how to get selected value from the list and then return that value to the main function so that I can use that value in somewhere else . Can someone help me please !!!!
####
self.device_list_store = gtk.ListStore(str,str,str,str,str)
for device in self.get_dev_list():
self.device_list_store.append(list(device))
device_list_treeview = gtk.TreeView(self.device_list_store)
selected_row = device_list_treeview.get_selection()
selected_row.connect("changed",self.item_selected)
####
def item_selected(self,selection):
model,row = selection.get_selected()
if row is not None:
selected_device = model[row][0]
at the moment ,the item_selected function is not returning anything , I want to return selected_device back to the main function so I can use it in other functions as well .
EDIT: I've edited code above to remove formatting errors #jcoppens
As you can see in the documentation, the item_selected function is called with one parameter, tree_selection. But if you define the function inside a class, it requires the self parameter too, which is normally added automatically. In your (confusing) example, there is no class defined, so I suspect the problem is your program which is incomplete.
Also, I suspect you don't want device_list_treeview = gtk.T... in the for loop:
for device in self.get_dev_list():
self.device_list_store.append(list(device))
device_list_treeview = gtk.TreeView(self.device_list_store)
And I suspect you want selected_device = mod... indented below the if:
if row is not None:
selected_device = model[row][0]
Please convert your example in a complete program, and formatted correctly.
BTW: item_selected is not a good name for the signal handler. It is also called if the item is unselected (which is why the signal is called 'changed')!
And important: Even though you should first read the basic Python tutorials and Gtk tutorials, you should then consider using lazka's excellent reference for all the Python APIs. There's a link on the page to download it completely and have it at hand in your computer.
Related
As I continue to study For Loops: I've run into some annoying errors. The problem is the script does exactly what I want it to. It deletes the null groups under the demo joints: but unlike other loops I've made for renaming which can be closed with a transform flag in the cmds.ls command: cmds.listRelatives doesn't allow a transform flag to close out the loop. You run the script by simply clicking Build Examples then hitting Delete Waste Groups
I've tried every flag according to the Maya documentation: but nothing seems to be closing the loop. I dont know if I need another variable, or a combination of some flags: or if I am using the wrong type of wording: but ideally what I would like this script to do is simply close out the loop so I dont get the error Error: No object matches name: curve
'''
import DS_wasteGroup_cleanerDemo
reload (DS_wasteGroup_cleanerDemo)
DS_wasteGroup_cleanerDemo.gui()
'''
import re
import maya.cmds as cmds
import maya.mel as mel
if cmds.window("renameWin", exists =True):
cmds.deleteUI("renameWin", window = True)
myWindow = cmds.window("renameWin",t='DS_wasteGroup_cleanerDemo',w=200, h=500, toolbox=True)
column = cmds.columnLayout(adj=True)
def gui():
cmds.button( label="Build Examples", c = buildExamples)
cmds.separator( w=200, h=3)
cmds.button( label="Delete Waste Groups", c = deleteWasteGrp)
cmds.separator( w=200, h=9)
cmds.setParent('..')
cmds.showWindow(myWindow)
def buildExamples(*args):
cmds.group(n='exampleGroup1',world=True,empty=True)
cmds.joint(n='demoJoint1')
cmds.group(n='curve1',world=True,empty=True)
cmds.parent('curve1','demoJoint1')
cmds.joint(n='demoJoint2')
cmds.parent('demoJoint2','exampleGroup1')
cmds.group(n='curve2',world=True,empty=True)
cmds.parent('curve2','demoJoint2')
cmds.joint(n='demoJoint3')
cmds.parent('demoJoint3','exampleGroup1')
cmds.group(n='curve3',world=True,empty=True)
cmds.parent('curve3','demoJoint3')
cmds.joint(n='demoJoint4')
cmds.parent('demoJoint4','exampleGroup1')
cmds.group(n='curve4',world=True,empty=True)
cmds.parent('curve4','demoJoint4')
cmds.joint(n='demoJoint5')
cmds.parent('demoJoint5','exampleGroup1')
cmds.group(n='curve5',world=True,empty=True)
cmds.parent('curve5','demoJoint5')
def deleteWasteGrp(*args):
grpList = cmds.listRelatives('demoJoint*',p=True,f=True)
for name in grpList:
print(grpList)
cmds.delete('curve*')
My apologies if I'm posting simple questions. I do write Python scripts to automate the most tedious tasks in rigging: but my knowledge is only intermediate. I want to learn more python so my scripts arent so clunky and brute forced: as well as the fact that I need them to be more adaptable to various types of characters: so any resources that dumb all this down would also be appreciated. Thank you for your help.
The error is correct, because the very first time the for loop executes, all "curve" obects are deleted, then in the next iteration, the same command does not find any curve objects because they are already deleted. If you place the delete command outside the for loop, the error should disappear.
Honestly I would take a whole different approach as you're hard-coding everything which could easily lead to disaster. When I mean hard-code, I mean you're trying to parent, let's say, "demoJoint2" to an object. This is bad because why are you assuming that "demoJoint2" even exists? If you create an object with a specific name that already exists, Maya will auto-rename the new object, and now you're referencing the wrong one right off the bat! Instead when you create your objects, capture their names in a variable then work with that, otherwise you'll be constantly shooting yourself in the foot.
Here's the same script with an approach I would try instead:
import maya.cmds as cmds
def gui():
if cmds.window("renameWin", exists=True):
cmds.deleteUI("renameWin", window=True)
myWindow = cmds.window("renameWin", t="DS_wasteGroup_cleanerDemo", w=200, h=500, toolbox=True)
column = cmds.columnLayout(adj=True)
cmds.button(label="Build Examples", c=buildExamples)
cmds.separator(w=200, h=3)
cmds.button(label="Delete Waste Groups", c=deleteWasteGrp)
cmds.separator(w=200, h=9)
cmds.setParent("..")
cmds.showWindow(myWindow)
def buildExamples(*args):
root = cmds.group(n="exampleGroup1", world=True, empty=True)
for i in range(5): # Loop to the amount of joints you want to create.
jnt = cmds.createNode("joint", name="demoJoint" + str(i + 1)) # Use `i` to help name the object.
jnt = cmds.parent(jnt, root)[0] # Parenting changes its long name, so recapture the joint in a variable.
crv = cmds.group(n="curve" + str(i + 1), world=True, empty=True) # Create empty group.
cmds.parent(crv, jnt) # Parent curve to joint.
def deleteWasteGrp(*args):
jnts = cmds.ls("demoJoint*", long=True, type="joint") # Get all `demoJoints`.
children = cmds.listRelatives(jnts, f=True, children=True, type="transform") or [] # Get all of their children, and only get transform types.
curves = [obj for obj in children if obj.split("|")[-1].startswith("curve")] # Don't assume we got the right objects. Run a final loop to collect any object that starts with `curve`. Need to use split as we're looping through long names but need to check its short name.
if curves: # `cmds.delete` will error if this list is empty, so don't assume.
cmds.delete(curves) # Delete all curves at once.
gui()
Now I can hit the build button as much as I want with no issues, and delete all the curves when pressing the delete button.
A few more notes:
Notice in buildExamples I'm using a loop to create all the objects instead of reusing redundant code that does the same thing. You could even have a spinbox in your gui that defines how many joints it creates now, where as before it wasn't possible because the count was hard-coded.
cmds.listRelatives does have a way to filter objects by transforms by setting parameter type="transform". In fact you'll see many commands have this same parameter (again start checking docs).
cmds.listRelatives('demoJoint*',p=True,f=True) was grabbing the joint's parent, not its children. The docs clearly state this.
Running cmds.delete('curve*') is going to delete ALL objects with names that start with curve, and since you're running this in a loop it's trying to do this multiple times.
maya.cmds is not pymel. There's a whole separate module called pymel.
If you're unsure with any parts of the code try adding in a print statement to see what it's doing.
I feel like you're going about this whole process a bit wrong, and I would love to elaborate if you're interested, but for now here is a fix for your loop situation:
def deleteWasteGrp(*args):
curveList = cmds.ls('curve*',transforms=True)
try:
cmds.delete(curveList)
print('Deleted the following objects: {}'.format(curveList))
except Exception as e:
cmds.warning('Cleanup failed: {}'.format(e))
The cmds.delete method accepts a list parameter, which in your case is the easiest way to get the job done. Keep in mind that when you delete a parent object, you also delete its children, so depending on your circumstances deleting objects can be order-specific.
Throwing any "likely to fail" calls in a try/except clause is generally a good idea, as it lets you handle the error gracefully. Be careful, however, to not suppress it and just move on -- you at the very least need to alert the user adequately.
Lastly, your buildExamples method will most likely fail if you run it more than once. Because you are addressing objects by string literals (hard coded names) instead of keeping track of their actual names (and full path). You will likely see this error eventually:
# Error: ValueError: file <maya console> line ??: More than one object matches name: demoJoint1 #
Edit: Some elaborations as requested
The commands cmds.group and cmds.joint return a string value indicating the actual name of the object created (in create mode). It's usually a good idea of storing this value in case Maya decides to name your object slightly differently than what you are expecting, usually when there is a naming clash. Eg:
print cmds.group(name='test', world=True, empty=True)
# Returns: test
print cmds.group(name='test', world=True, empty=True)
# Returns: test1
Example of how to capture object names as you create them. I've concatenated your five identical(ish) calls to create joints and curves in this loop:
import maya.cmds as cmds
topGroupName = 'exampleGroup'
actualTopGroupName = None
# Create top level group
actualTopGroupName = cmds.group(n=topGroupName, world=True, empty=True)
# Loop through 5 times and do the following:
for i in range(5):
# PS: hash character in name indicates "next available number"
cmds.select(clear=True)
jnt = cmds.joint(n='demoJoint#')
crv = cmds.group(n='curve#',world=True,empty=True)
cmds.parent(crv, jnt)
cmds.parent(jnt, actualTopGroupName)
Example of how to narrow down which objects to search for with cmds.ls:
topGroupName = 'exampleGroup'
print cmds.ls('|{}*|*|curve*'.format(topGroupName))
# Returns: [u'curve1', u'curve2', u'curve3', u'curve4', u'curve5']
# The string .format() expression is just a dynamic way of writing this:
# |exampleGroup*|*|curve*
Vertical pipes (|) indicate levels in a hierarchy, similar to how slashes (/) work in URLs. And asterisks/wildcards (*) indicate "any character, or none".
Hope this helps you along your way a little bit.
I am creating a REPL tool for my project that (simplified for clarity) either directly executes entered commands or (if a command ".x some/path/to/file" is entered) reads and executes them from file. My question is related to auto-completing the user input (using prompt_toolkit).
I have something like (minimum executable example):
import prompt_toolkit
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.document import Document
from prompt_toolkit.contrib.completers import PathCompleter
class CommandCompleter(Completer):
def __init__(self):
self.path_completer = PathCompleter()
self.commands = [".x", "command1", "command2"]
def get_completions(self, document, complete_event):
if document.text.startswith(".x "):
sub_doc = Document(document.text[3:])
yield from (Completion(cmd.text, -document.cursor_position)
# ???????? ?????????????????????????
for cmd
in self.path_completer.get_completions(sub_doc, complete_event))
# ???????
else:
yield from (Completion(cmd, -document.cursor_position)
for cmd in self.commands
if cmd.startswith(document.text))
if __name__ == "__main__":
while True:
other_args = {}
input = prompt_toolkit.prompt(">>> ", completer=CommandCompleter(), **other_args)
# Do something with input (omitted)
The second if-branch (for commands) works correctly but I don't know how to properly call the PathCompleter.get_completions() method and reconstruct the Completion objects from its result (where the ???'s are) in the first branch. The trick is that I am using the completion only for a part of the input and various sub-stringing, position calculations etc. did not (yet) lead to the satisfactory behaviour (i.e. offering the paths and constructing the correct input line).
I will definitely go on searching but if anyone knows how to rewrite this, it would be very useful.
Note: yield from self.path_completer.get_completions(document, complete_event) would be used if the whole input would be just the path (and this works correctly).
Probably the following should fix it:
sub_doc = Document(document.text[3:])
yield from (Completion(completion.text, completion.start_position, display=completion.display)
for completion
in self.path_completer.get_completions(sub_doc, complete_event))
completion.text contains the text that is going to be inserted;
completion.start_position contains the place where the text is going to be inserted, relative to the cursor position (in this particular example we can take the value from the nested completer).
completion.display is the value displayed in the pop-up menu. (In this case, the whole filename, rather than only the inserted string.
Feel free to open a GitHub issue if you have any more questions.
introducing that I'm new in python, I'm tring to use the intField command to set a number of iterations for this attribute: 'aiSubdivIterations'.
The script should work like that: when I run the scripts it open a window where I can set my value and when I press enter it should automatically set the same value in the 'aiSubdivIterations' slot.
import maya.cmds as pm
def aiSetIter(iterValue):
objSelect= pm.ls(sl=1, dag=True, leaf=True)
for obj in objSelect:
pm.setAttr( obj + '.aiSubdivIterations', iterValue)
pm.window(title = 'Interations')
pm.columnLayout ('mainColumn', adjustableColumn = True)
pm.gridLayout ('nameGridLayout01', numberOfRowsColumns = (2,2), cellWidthHeight = (80,30), parent = 'mainColumn')
pm.text (label = 'number')
pm.intField (minValue=0, maxValue=10, step=1, vcc = 'aiSetIter(iterValue)')
pm.showWindow()
Could some one help to make this script working?
Thanks in advance
Flavia
the easiest for your script to work is to just specify the function you want to call (with no arguments and the rest of your code unchanged):
pm.intField('valueField', minValue=0, maxValue=10, step=1, vcc=aiSetIter)
You can assume that Maya's intField will call the specified function by automatically passing the value it stores.
In the above case, your function will be called only when the UI is made visible or closed.
If you need your function to be called every time the value changes, you want to add a "changeCommand" (or "cc") flag too:
pm.intField('valueField', minValue=0, maxValue=10, step=1, vcc=aiSetIter, cc=aiSetIter)
For more complex scenarios, you might want to consider lambda functions (you can read here a nice post about it); this will allow delayed evaluation of your function.
What follows is a super-simple example of a lambda function retrieving the current time when the intField value changes and passing it, along with the value itself, to myLambdaFunc:
import maya.cmds as pm
import time
def myLambdaFunc(iterValue, now):
print iterValue, now
lambdafunc = lambda arg: myLambdaFunc(arg, time.time())
pm.window(title='Iterations')
pm.columnLayout ('mainColumn', adjustableColumn=True)
pm.gridLayout ('nameGridLayout01', numberOfRowsColumns=(2,2), cellWidthHeight=(80,30), parent='mainColumn')
pm.text (label='number')
pm.intField('valueField', minValue=0, maxValue=10, step=1, vcc=lambdafunc, cc=lambdafunc)
pm.showWindow(win)
EDIT:
A minor integration, since I bumped into this just now:
https://theodox.github.io/2014/maya_callbacks_cheat_sheet
It is a useful and exhaustive article by theodox about Maya UI and callbacks, found via this; worth a read.
I have a wxPython GUI with a very large grid. I am using similar code to the GridHugeTable.py example from the wxPython demo -- i.e., using PyGridTableBase to make a virtual grid.
I am running into trouble when I try to interactively add columns to this grid, however.
Calling AppendCols(1) results in this error:
wx._core.PyAssertionError: C++ assertion "Assert failure" failed at /Users/vagrant/pisi-64bit/tmp/wxPython-3.0.2.0-3/work/wxPython-src-3.0.2.0/src/generic/grid.cpp(1129) in AppendCols():
Called grid table class function AppendCols but your derived table class does not override this function
But if I try to overwrite AppendCols in my table class, the application just hangs indefinitely and never resolves. It hangs even if there is actually nothing in my custom AppendCols method at all...
class HugeTable(gridlib.PyGridTableBase):
"""
Table class for virtual grid
"""
def __init__(self, log, num_rows, num_cols):
gridlib.PyGridTableBase.__init__(self)
def AppendCols(self, *args):
pass
I've been able to overwrite other methods successfully, (setValue, getValue, getColLabelValue, etc.), so I'm not sure what is different here.
Update:
I returned to this problem after a while away. I no longer get the wx.__core.PyAssertionError. However, I still can't get my custom AppendCols method to work. I can't figure out what to put in AppendCols to make a new column actually show up.
I'm not sure how to look in the source code -- none of the Python documentation seems to have what I'm looking for, so maybe I need to go digging in wxWidgets? The documentation hasn't helped: https://wiki.wxpython.org/wxPyGridTableBase.
The clue I needed is in the the demo code for custom table.
So, this code works (leaving out my custom logic and just including the bare bones):
def AppendCols(self, *args):
msg = gridlib.GridTableMessage(self, # The table
gridlib.GRIDTABLE_NOTIFY_COLS_APPENDED, # what we did to it
1) # how many
self.GetView().ProcessTableMessage(msg)
return True
I'm having a little bit of trouble assigning values to a QLineEdit. I've read the documentation and feel that the QLineEdit.SetText() command will be used at some point.
I've used Qt Designer to design a GUI for my software. On the main window (MainWindow.py, with an accompanying ui_MainWindow.py setup file), I have a LineEdit (lineEditScanBarcode) which has strong focus. I've managed to pull input from that LineEdit pretty well. What I'd like to do is this:
If the input in LineEditScanBarcode = x, then assign the name 'John Smith' to a secondary QLineEdit (lineEditUser) which has a zero focus policy. This is what I have so far:
def ScanBarcode(self):
barcode = self.lineEditScanBarcode.text()
self.lineEditScanBarcode.clear()
if barcode == '12345':
print("Welcome John")
self.lineEditUser.setText() = 'John'
else: print("Sorry, user not recognised.")
Upon running this, I get the following error:
Syntax Error: can't assign to function call
I've had a look at the above error, but I'm still unsure as to what's going on here. I still have no idea to open one window on top of another (this software package will have about 10 windows), but that's another story!
Is my logic here on track? I've never used Qt before, so my understanding of the intricacies involved is lacking to say the least.
Any input would be great!
As the comment states, the error is on this line:
self.lineEditUser.setText() = 'John'
You are attempting to assign the value 'John' to that functioncall (as the error states). If you review the documentation for QLineEdit in PyQT, you'll see that QLineEdit.setText() requires a string to be passed to it.
So, what you need to do instead is pass the value 'John' to the function like so:
self.lineEditUser.setText('John')
On another note your idea that your
software package will have about 10 windows
is definitely something that you want to reexamine. More windows, especially when undocked and floating independently will no doubt cause usability issues. I'd strongly recommend sharing your ideas over at UserExperience.SE.