In my project, I have to connect .Net with the QGIS app, so I need to know how an outside script can get data from QGIS.
I can run this script from .Net perfectly:
from qgis.PyQt.QtWidgets import QMessageBox
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
import sys
import os
def main ():
# Create a reference to the QgsApplication.
# Setting the second argument to True enables the GUI. We need
# this since this is a custom application.
strRuta = r"C:\Program Files\QGIS 3.22.11\apps\qgis-ltr"
os.environ['QGIS_PREFIX_PATH'] = strRuta
# load providers
qgs = QgsApplication([], True)
# Supply the path to the qgis install location
qgs.setPrefixPath(strRuta, True)
qgs.initQgis()
# QgsApplication.setPrefixPath(r"C:\Program Files\QGIS 3.22.11\apps\qgis-ltr", True)
QMessageBox.warning(None, "AVISO", QgsApplication.showSettings())
project = QgsProject.instance()
listLayers = QgsProject.instance().mapLayersByName('MONTE')
QMessageBox.information(None, "Aviso monte:", str(len(listLayers)))
# Write your code here to load some layers, use processing
# algorithms, etc.
# Finally, exitQgis() is called to remove the
# provider and layer registries from memory
qgs.exitQgis()
if __name__ == "__main__":
main()
However, in this line QMessageBox.information(None, "Aviso monte:", str(len(listLayers)))
, I obtain 0, but I have charged a MONTE layer in qgis manually without code
I am using QGIS 3.22.11.
-
Please, do not forget about "What should I do when someone answers my question?"Taras– Taras ♦2023年02月04日 11:28:51 +00:00Commented Feb 4, 2023 at 11:28
1 Answer 1
You have to load a project. QgsProject.instance()
returns the empty project, because you didn't load any project.
Add this line: project.read("c:/path/to/project.qgz")
project = QgsProject.instance()
project.read("c:/path/to/project.qgz")
listLayers = QgsProject.instance().mapLayersByName('MONTE')
QMessageBox.information(None, "Aviso monte:", str(len(listLayers)))
-
Yes, but I have some layers in qgis that I have imported from postgis, and I would like to make some operations with them in this script. Is there any way to do this?Andrés Rodríguez– Andrés Rodríguez2022年12月29日 20:30:03 +00:00Commented Dec 29, 2022 at 20:30
-
How can I access to the project and the layers that are charged in qgis from this script ?Andrés Rodríguez– Andrés Rodríguez2022年12月30日 13:30:59 +00:00Commented Dec 30, 2022 at 13:30
Explore related questions
See similar questions with these tags.