Revit API Selection
This is the base imports and variables that you might need for code snippets below…
This is the base imports and variables that you might need for code snippets below…
from Autodesk.Revit.DB import *
from Autodesk.Revit.UI.Selection import ISelectionFilter, Selection, ObjectType
doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument
selection = uidoc.Selection
Get elements that are currently selected in Revit UI. It also includes selection of views and sheets in ProjectBrowser menu.
sel_elem_ids = uidoc.Selection.GetElementIds()
sel_elems = [doc.GetElement(e_id) for e_id in sel_elem_ids]
filtered_elements = [el for el in sel_elems if type(el) == Wall]
Pick Elements by Rectangle
Prompt user selection by clicking and dragging a rectangular area in Revit space.
selected_elements = uidoc.Selection.PickElementsByRectangle('Select some Elements.')
print(selected_elements)
Prompt user to pick and element.
from Autodesk.Revit.UI.Selection import ObjectType
ref = uidoc.Selection.PickObject(ObjectType.Element)
picked_object = doc.GetElement(ref)
print(picked_object)
Prompt user to pick multiple elements. User have to confirm selection by clicking 'Finish' in top left corner of UI.
from Autodesk.Revit.UI.Selection import ObjectType
refs = uidoc.Selection.PickObjects(ObjectType.Element)
picked_objects = [doc.GetElement(ref) for ref in refs]
for el in picked_objects:
print(el)
Prompt user to pick a point in Revit space.
selected_pt = uidoc.Selection.PickPoint()
print(selected_pt, type(selected_pt))
Prompt user to pick a box area in Revit space.
from Autodesk.Revit.UI.Selection import PickBoxStyle
picked_box = uidoc.Selection.PickBox(PickBoxStyle.Directional)
print(picked_box)
print(picked_box.Min)
print(picked_box.Max)
Set Selection in Revit UI
Modify user's selection in Revit UI.
Notice that you have to create a List[ElementId] instead of python list to provide in SetElementIds method.
import clr
clr.AddReference('System')
from System.Collections.Generic import List
wall_ids = FilteredElementCollector(doc).OfClass(Wall).ToElementIds()
List_wall_ids = List[ElementId](wall_ids)
uidoc.Selection.SetElementIds(List_wall_ids)
BONUS: Advanced Selection Filtering
To improve user experience you can pre-define what elements are allowed to be selected using ISelectionFilter interface. Just create a class and specify rules inside AllowElement method that return True to allow selection.
from Autodesk.Revit.UI.Selection import ISelectionFilter, ObjectType
class custom_filter(ISelectionFilter):
def AllowElement(self, element):
if type(element) == Wall:
return True
el_ids = uidoc.Selection.PickObjects(ObjectType.Element, custom_filter())
sel_elems = [doc.GetElement(el_id) for el_id in el_ids]
print(sel_elems)