I have been piecing code together from a number of posts to python outside of QGIS that will open a QGIS instance and then load specific data I feed it. I am not to familiar with using the QGIS API commands, so I am a bit lost. I assume that I am not properly pointing to the instance that is being open. Seems like there are a lot of questions revolving around this topic, but I haven't been able to find something up to date (QGIS 3.16) or that uses scripting outside of the QGIS shell.
Any suggestions?
from qgis.core import *
from qgis.utils import *
from qgis.gui import *
app_path = "C:/Program Files/QGIS 3.16/bin/qgis-ltr-bin.exe"
def open_app(application_path):
subprocess.call(application_path)
def open_layers():
qgishome = "C:/Program Files/QGIS 3.16/apps/qgis-ltr/"
app = QgsApplication([], True)
QgsApplication.setPrefixPath(qgishome, True)
QgsApplication.initQgis()
vlayer = QgsVectorLayer("D:/my_shapefile.shp", 'layer', 'ogr')
### EDITS ###
ex = vlayer.extent()
canvas = QgsMapCanvas()
canvas.setExtent(ex)
### EDITS ###
QgsProject.instance().addMapLayer(vlayer)
def main():
open_app(app_path)
open_layers()
if __name__ == "__main__":
main()
Class Edits
With the advice from @J. Monticolo I created a class and defined self.canvas
, but the same problem occurs. A small window appears and disappears as if the app loads and exits. I'll admit, I have not worked with classes much so I am a bit rusty.
class Test():
def __init__(self):
pass
def open_layers(self):
qgishome = "C:/Program Files/QGIS 3.16/apps/qgis-ltr/"
app = QgsApplication([], True)
QgsApplication.setPrefixPath(qgishome, True)
QgsApplication.initQgis()
vlayer = QgsVectorLayer("D:/my_shapefile.shp", 'layer', 'ogr')
self.canvas = QgsMapCanvas()
ex = vlayer.extent()
self.canvas = QgsMapCanvas()
self.canvas.setExtent(ex)
QgsProject.instance().addMapLayer(vlayer)
self.canvas.show()
def main():
app = Test()
app.open_layers()
QgsMapCanvas
(used this post for reference). The code runs without error, but it does not open QGIS.exe and load the layer. That is why I had thesubprocess.call(application_path)
.app
somewhere?qgishome
variable need to be pointing to an executable?open_layers()
that fixes the window from disappearing. But the window that is loaded looks almost like a white terminal that cannot do anything. It is not a QGIS instance.