Button and context menu options on component through GhPython



Like this component, it has an Update button, and 3 option list if you Right-Click this.
Is it possible to achieve that through GHpython after compiling into ghpy file?


(Giulio Piacentino) #3

OK-- so, this needs a little bit of introduction.

Both are possible also in GhPython. I am going to introduce the context menu, because it really sometimes is required. But I am not going to show the button, because this deviates from the default way of doing thngs in Grasshopper and so I will leave it as an exercise if you really think it’s necessary.

The GhPython component provides a dynamic binding to the underlying AppendAdditionalMenuItems function of GH_Component*. Therefore, all you really have to do it override it. In Python this really just mean define a member with the same name.

The method we are overriding is AppendAdditionalMenuItems: http://developer.rhino3d.com/api/grasshopper/html/M_Grasshopper_Kernel_GH_Component_AppendAdditionalMenuItems.htm

As you can see, it gives us an object guaranteed to be derived from type ToolStripDropDown: https://msdn.microsoft.com/en-us/library/fs7t9bea

We just need to add a new item. In turn, the item will contain some text, optionally an image and a link to a method that needs to be called when the item is clicked.

Here is the file.
AppendAdditinalMenuItems-python.gh (3.9 KB)

*when you compile, you really derive from GH_Component, thereby having access to exactly the same class. At runtime while editing, GhPython simply binds a list of methods to its own underlying GH_Component. Because of duck-typing, this will look exactly like overriding the method, but we will be able to switch many times the implementation, which is something that is not possible in normal C# development, but rather requires a Rhino restart.


Thank you Giulio,that would be very helpful!


That’s awesome! Would that mean we can override DrawViewportMeshes and DrawViewportWires now? And if so, could you maybe provide a small example of how, pretty please :slight_smile:

(Giulio Piacentino) #6

Yes, both are true. An example can be found in this post.
Now that GhPython is distributed with Rhino 6 and 6 has shipped, this becomes more useful.


Ah yes, of course, that takes me back. This really is terrific. Great job guys :clap: