3

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.

Taras
35.7k5 gold badges77 silver badges151 bronze badges
asked Dec 29, 2022 at 13:24
1

1 Answer 1

5

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)))
Taras
35.7k5 gold badges77 silver badges151 bronze badges
answered Dec 29, 2022 at 13:51
2
  • 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? Commented Dec 29, 2022 at 20:30
  • How can I access to the project and the layers that are charged in qgis from this script ? Commented Dec 30, 2022 at 13:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.