I'm sure there are ways to do this directly, but I've had the best experience importing and exporting vectors layers indirectly, QGIS <> GPKG <> KML. You have more flexible control of the conversion options to/from KML that way than QGIS <> KML using the standard input drivers. (This is certainly true with GUI import/export, not sure about what you can control direct with PyQGIS).
Basically, create a test GPKG from your layers and then use ogr2ogr
, playing around with the options (in particular look at -oo
, -doo
, -lcso
, -dsco
), using https://www.gdal.org/drv_libkml.html as reference. Make sure to use the LIBKML driver not the KML driver. Once you have found what you need using the ogr2ogr
command line utility, implement it in Python using gdal.vectorTranslate
since you can specify the same options in its arguments.
For an example going the other way (KML to GPKG to displayed map layers), see my question QGIS/QDAL: Accessing OGR_STYLE across all layers in a KML file.
What you can hope to pass fully automatically as styling is limited, and you'll likely do best to pick out and pass what you really care about via an explicit OGR_STYLE
attribute in your layer, either specified directly using the specification at https://www.gdal.org/ogr_feature_style.html (I've never done this), or using an @namedstyle
that you then (re)define manually as a styleURL
(with a # not a @) in the KML file using KML's more restricted styling options.
Updating to add: You should be able to actually write KML directly (without the GPKG intermediary) using VectorTranslate
, passing your layer's data source as a parameter I think. It's still klugey, but less so, and retains the flexibility to control the LIBKML driver fully.
You could also just try creating a OGR_STYLE
attribute in the layer (or a throwaway memory copy) and then just saving the layer as KML normally (without the overhead of VectorTranslate
). I'm not sure if the appropriate ogr
options are turned on by default to convert that specially named attribute into layer- and/or feature-specific styling in the KML file, however, especially given what you've written about trouble passing the whole attribute table (I'm not familiar with that, sorry).