Search code examples
pythonrevitrevitpythonshell

Problem with GetElementIds() to get current selection


I have a small code to extract current selection from revit but I get an error saying expected selection ,got list[elementId]

I also tried passing GetElementIds() as in the API but it says it takes excatly 1 argument(0 given)

import clr
import System
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI.Selection import *

clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)

clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager

# Import iron python packages
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)



app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document

#get current selection from Document

from Autodesk.Revit.UI import Selection
from System.Collections.Generic import List as CL

sel = CL[ElementId]()
Selected=Selection.Selection.GetElementIds()
print(len(Selected))

Solution

  • the error in in this line of code:

    Selected=Selection.Selection.GetElementIds()
    

    You need to add a link to the ui, then you can use it to get the selection:

    ui = __revit__.ActiveUIDocument
    Selected=ui.Selection.GetElementIds()
    

    Here is a full code that will fetch the users selection:

    import clr
    clr.AddReference('RevitAPI') 
    clr.AddReference('RevitAPIUI') 
    app = __revit__.Application
    doc = __revit__.ActiveUIDocument.Document
    ui = __revit__.ActiveUIDocument
    
    selectedElements = []
    for elementId in ui.Selection.GetElementIds():
        selectedElements.Add(doc.GetElement(elementId))
    
    for item in selectedElements:
        print item