Summary
Selection Class
To control selection in Revit with python we need to use Selection Class.
It has plenty of helpful methods. So let's go through most used ones for selection and understand how to use them.
Methods:
GetElementIds
PickElementsByRectangle
PickObject
PickObjects
SetElementIds
PickBox
PickPoint
Get Selection Instance
To use any of these methods we need to get an instance of Selection Class.
Luckily, there is a property .Selection in our uidoc instance. So it's very simple to get it
💡We can also specify type of a variable so pyCharm can give us better autosuggestions by using '#type: …' syntax.
👆 We will need that for all the snippet below!
GetElementIds Method
This method will return list of ElementId of your current selection in Revit UI. I love using it, as it can be a very quick approach to select elements.
Since this method returns us ElementIds, don't forget to turn them into actual elements, so we can read their properties and methods.
💡Optionally, we can also introduce very basic filter by checking type of elements.
PickElementsByRectangle Method
This method is great, because it's a single line of code, and it already returns you list of Elements instead of ElementIds.
But unfortunately, there is no confirmation needed on your selection. So if you selected wrong elements, you would need to run your tool again to correct it. And if you want to fix that, PickObjects is going to solve that issue for you.
PickObject Method
This is great for selecting a single element.
But be aware that it returns a Reference. Luckily, we can use the same doc.GetElement() method and provide reference instead of an ElementId.
💡 We can also create a for/while loop and ask user to select single element over and over and do something with it. For example we could change color overrides of each element one by one by clicking on them.
PickObjects Method
This method is similar to single PickObject. But this time we would need a list comprehension to convert all references to actual elements.
SetElementIds Method
We use this method whenever we want to change selection in Revit UI.
It takes a single argument - ICollection[ElementId] that includes new selection.
PickPoint Method
We can also ask user for a location input such as Point. This might be great for many tools.
💡 Points are represented with XYZ class in Revit API. Also pay attention as it uses feet for X,Y,Z coordinates in Internal Coordinate System.
PickBox Method
Alternatively, we can ask user to Pick a Box. PickedBox has properties to get 2 points:
HomeWork
👉 Now you have all the main snippets for selecting elements with Revit API. Now it's your turn to practice
✅ Try to select elements with snippets and print results.
✅ Place Snippets that you are going to reuse in lib
⌨️ Happy Coding!