In PyQGIS 3, how can I convert selected polygons with n sides, into another layer with n lines?

import processing

mapcanvas = iface.mapCanvas()
layer = mapcanvas.currentLayer()
features = layer.getFeatures()

line_path = "C:/Users/Me/Desktop/pyqgis/line.shp"

#### I need something like this processing method, but instead of a polygon in the input, i need the selected feature. 
#processing.run("qgis:polygonstolines", {'INPUT': polygon_path,'OUTPUT': line_path}

Firstly, you can extract selected polygons to memory, secondly convert them to lines, then explode the lines.

This script works in QGIS 3.8, but it doesn't in QGIS 3.4.13:

import processing

layer = iface.activeLayer()
selected = processing.run("native:saveselectedfeatures", {'INPUT':layer, 'OUTPUT':'TEMPORARY_OUTPUT'})["OUTPUT"]    
temp_lines = processing.run("native:polygonstolines", {'INPUT': selected, 'OUTPUT':'TEMPORARY_OUTPUT'})["OUTPUT"]

line_path = "C:/Users/Me/Desktop/pyqgis/line.shp"
processing.runAndLoadResults("native:explodelines", {'INPUT': temp_lines, 'OUTPUT': line_path})

This script works in both QGIS 3.4.13 and 3.8:

import processing

layer = iface.activeLayer()
selected = processing.run("qgis:saveselectedfeatures", {'INPUT':layer, 'OUTPUT':'memory:'})["OUTPUT"]    
temp_lines = processing.run("qgis:polygonstolines", {'INPUT':selected,'OUTPUT':'memory:'})["OUTPUT"]

line_path = "C:/Users/Me/Desktop/pyqgis/line.shp"   
result = processing.run("qgis:explodelines", {'INPUT':temp_lines,'OUTPUT':'memory:'})["OUTPUT"]
| improve this answer | |
  • Thanks, but i had this error message in console: Traceback (most recent call last): File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py" .... File "C:/PROGRA~1/QGIS3~1.4/apps/qgis-ltr/./python/plugins\processing\tools\general.py", line 105, in run return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context) File "C:/PROGRA~1/QGIS3~1.4/apps/qgis-ltr/./python/plugins\processing\core\Processing.py", line 127, in runAlgorithm raise QgsProcessingException(msg) _core.QgsProcessingException: Error: Algorithm native:polygonstolines not found – vitorcsm Jan 16 at 22:35
  • What is the version of QGIS you use? I don't encounter that error. – Kadir Şahbaz Jan 17 at 18:49
  • 3.4.14 - Madeira – vitorcsm Jan 17 at 21:41
  • I didn't found the answer, please, can you help me? – vitorcsm Jan 21 at 13:06
  • I don't get any error when I use the script. Therefore I have no idea what the problem is. – Kadir Şahbaz Jan 21 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.