Delete all footprints with certain field value in the schematic

I want to delete all footprints which have a certain value in a field in the schematic so that I can generate a custom paste layer Gerber which contains only certain footprints. I started writing a Python script but there seems to be no way (KiCad Pcbnew Python Scripting: pcbnew Namespace Reference) to access the schematic field values from within PCBNew. Is that so or any other idea? :smiley:

Ok, I managed somehow to find something in the depths of the Doxygen documentation. For who is curios:

#!/usr/bin/python3
import pcbnew
import wx

class DeleteComponentsPlugin(pcbnew.ActionPlugin):
    def defaults(self):
        self.name = "Delete Components Without EC=YES"
        self.category = "Modify PCB"
        self.description = "Deletes all components that don't have 'YES' in the 'EC' field"

    def Run(self):
        # Get the current board
        board = pcbnew.GetBoard()

        # Get all modules (footprints) on the board
        modules = board.GetFootprints()

        # List to store modules to be removed
        to_remove = []

        # Iterate through all modules
        for module in modules:
            ec_value = ""
            # Get the reference item (which contains the fields)
            reference = module #.Reference()
            
            # Iterate through all fields
            for i in reference.GetFields(): ##range(reference.GetFieldCount()):
                field = i #reference.GetField(i)
                if field.GetName() == "EC":
                    ec_value = field.GetText()
                    break
            
            # If EC is not "YES", add to removal list
            if ec_value != "YES":
                to_remove.append(module)

        # If no modules to remove, show message and return
        if not to_remove:
            wx.MessageBox("No components found to remove.", "Info", wx.OK | wx.ICON_INFORMATION)
            return

        # Ask for confirmation before deleting
        dlg = wx.MessageDialog(None, 
                               f"This will delete {len(to_remove)} component(s). Are you sure?",
                               "Confirm Deletion", 
                               wx.YES_NO | wx.ICON_QUESTION)
        result = dlg.ShowModal()
        dlg.Destroy()

        if result == wx.ID_YES:
            # Remove the modules
            for module in to_remove:
                board.Remove(module)

            # Refresh the board
            pcbnew.Refresh()

            wx.MessageBox(f"Deleted {len(to_remove)} component(s).", "Success", wx.OK | wx.ICON_INFORMATION)
        else:
            wx.MessageBox("Operation cancelled.", "Cancelled", wx.OK | wx.ICON_INFORMATION)

DeleteComponentsPlugin().register()
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.