def qgisapp(args=None, guienabled=True, configpath=None, sysexit=True): """ Create a new QGIS Qt application. You should use this before creating any Qt widgets or QGIS objects for your custom QGIS based application. usage: from qgis.core.contextmanagers import qgisapp def main(app): # Run your main code block with qgisapp(sys.argv) as app: main(app) args - args passed to the underlying QApplication. guienabled - True by default will create a QApplication with a GUI. Pass False if you wish to create no GUI based app, e.g a server app. configpath - Custom config path QGIS will use to load settings. sysexit - Call sys.exit on app exit. True by default. """ if not args: args = [] app = QgsApplication(args, guienabled, configpath) QgsApplication.initQgis() yield app if guienabled: exitcode = app.exec_() else: exitcode = 0 QgsApplication.exitQgis() if sysexit: sys.exit(exitcode)
def main(argv): # create Qt application app = QtGui.QApplication(argv, True) # Set the app style mySplashPix = QtGui.QPixmap(QtCore.QString(DATA_DIR + '/OCEAN.png')) mySplashPixScaled = mySplashPix.scaled(500, 300, Qt.Qt.KeepAspectRatio) mySplash = QtGui.QSplashScreen(mySplashPixScaled) mySplash.show() # initialize qgis libraries QgsApplication.setPrefixPath(QGIS_PREFIX, True) QgsApplication.initQgis() # create main window wnd = MainWindow(mySplash) wnd.show() # Create signal for app finish app.connect( app, QtCore.SIGNAL('lastWindowClosed()'), app, QtCore.SLOT('quit()')) # Start the app up retval = app.exec_() # We got an exit signal so time to clean up QgsApplication.exitQgis() sys.exit(retval)
def qgisapp(args=None, guienabled=True, configpath=None, sysexit=True): """ Create a new QGIS Qt application. You should use this before creating any Qt widgets or QGIS objects for your custom QGIS based application. usage: from qgis.core.contextmanagers import qgisapp def main(app): # Run your main code block with qgisapp(sys.argv) as app: main(app) args - args passed to the underlying QApplication. guienabled - True by default will create a QApplication with a GUI. Pass False if you wish to create no GUI based app, e.g a server app. configpath - Custom config path QGIS will use to load settings. sysexit - Call sys.exit on app exit. True by default. """ if not args: args = [] app = QgsApplication(args, guienabled, configpath) QgsApplication.initQgis() yield app if guienabled: exitcode = app.exec_() else: exitcode = 0 QgsApplication.exitQgis() if sysexit: sys.exit(exitcode)
def main(args=None): # supply path to qgis install location QgsApplication.setPrefixPath("/usr", True) # create a reference to the QgsApplication # setting the second argument to True enables the IquaView GUI, # which we need to do since this is a custom application qgs = QgsApplication([], True) # init splash screen splash_pix = QPixmap(':/resources/iquaview.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) light_blue = QColor(165, 197, 192) dark_blue = QColor(11, 52, 70) # adding progress bar progress_bar = QProgressBar(splash) p = progress_bar.palette() p.setColor(QPalette.Highlight, light_blue) p.setColor(QPalette.HighlightedText, dark_blue) progress_bar.setPalette(p) progress_bar.setMaximum(10) progress_bar.setGeometry(0, splash_pix.height() - 50, splash_pix.width(), 20) splash.show() splash.showMessage("Initializing interface...", Qt.AlignBottom | Qt.AlignCenter, light_blue) # progress bar... for i in range(1, 11): progress_bar.setValue(i) t = time() if i == 5: splash.showMessage("Loading providers...", Qt.AlignBottom | Qt.AlignCenter, light_blue) # load providers qgs.initQgis() LOGGER.info(qgs.showSettings()) if i == 10: # exec iquaview window window = MainWindow() window.setWindowIcon(QIcon(":/resources/iquaview_vector.svg")) splash.showMessage("IQUAview ready!", Qt.AlignBottom | Qt.AlignCenter, light_blue) while time() < t + 0.1: qgs.processEvents() window.showMaximized() splash.finish(window) qgs.exec_() window.deleteLater() # when app terminates, call exitQgis() to remove the provider and layer registries from memory qgs.exitQgis()
def main(): qgs = QgsApplication([], True) qgs.setPrefixPath('qgis', True) qgs.initQgis() window = MapExplorer() window.show() exit_code = qgs.exec_() qgs.exitQgis() sys.exit(exit_code)
def main(): app = QApplication(sys.argv) QgsApplication.setPrefixPath(qgis_prefix, True) QgsApplication.initQgis() model = Model() ex = login.Window(model) r = app.exec_() QgsApplication.exitQgis() sys.exit(r)
def main(): QgsApplication.setPrefixPath("/usr", True) qgis = QgsApplication([], False) qgis.initQgis() params = argv[1:] if len(params) > 0: for param in params: create_sdl_for_fgdb_layers(param) else: print("Usage: create_sdl.py fgdb_path [fgdb_path2 ...]") qgis.exitQgis()
def run_qgis_algorithm(algorithm_id, algorithm_parameters): import sys import qgis.utils from qgis.core import ( QgsApplication, QgsProcessingFeedback, QgsVectorLayer, QgsProcessingProvider, QgsProcessingRegistry, ) from qgis.analysis import QgsNativeAlgorithms # See https://gis.stackexchange.com/a/155852/4972 for details about the prefix QgsApplication.setPrefixPath('/usr', True) qgs = QgsApplication([], False) qgs.initQgis() # # Append the path where processing plugin can be found sys.path.append('/usr/share/qgis/python/plugins/') import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) print('You are using QGIS version: %s ', qgis.utils.Qgis.QGIS_VERSION) print('You are running: %s ', algorithm_id) provider = NDVIProvider() provider.loadAlgorithms() QgsApplication.processingRegistry().addProvider(provider) # Checking if the algorithm is added # last_alg = QgsApplication.processingRegistry().algorithms()[-1] # print(last_alg.name()) # print(last_alg.id()) # last_alg = QgsApplication.processingRegistry().algorithms()[-2] # print(last_alg.name()) # print(last_alg.id()) # Show help for the algorithm processing.algorithmHelp(algorithm_id) print('Running algorithm') result = processing.run(algorithm_id, algorithm_parameters) print('### Result:') print(result) qgs.exitQgis() return result
def main(): app = QtGui.QApplication(sys.argv, True) # supply path to where is your qgis installed QgsApplication.setPrefixPath("/usr", True) # load providers QgsApplication.initQgis() # print QgsApplication.showSettings() mw = MainWindow() try: mw.create_layer(DATA) mw.show() app.exec_() finally: QgsApplication.exitQgis()
def main(argv): parser = argparse.ArgumentParser( "Generate QGIS projects or QGIS dataobjects yaml templates.") parser.add_argument("--generator", type=str, help="The generator to use. (Example: postgres)") parser.add_argument( "--uri", type=str, help="Database uri, used as db entry point. (Example: service=pg_qgep)", ) parser.add_argument( "out", type=str, help= "Path to the generated dataobjects. (Example: /home/qgis/my_project)", ) args = parser.parse_args() # Initialize qgis libraries QgsApplication([], True) QgsApplication.initQgis() def debug_log_message(message, tag, level): print("{}({}): {}".format(tag, level, message)) QgsApplication.instance().messageLog().messageReceived.connect( debug_log_message) generator_module = importlib.import_module("generator." + args.generator) generator = generator_module.Generator(args.uri) available_layers = generator.layers() relations, _ = generator.relations(available_layers) project = Project() project.layers = available_layers project.relations = relations qgis_project = QgsProject.instance() project.create(args.out, qgis_project) yamlfile = args.out + ".yaml" with open(yamlfile, "w") as f: f.write(yaml.dump(project.dump(), default_flow_style=False)) print("Project template written to {}".format(yamlfile)) QgsApplication.exitQgis()
def main(): parser = argparser_prepare() args = parser.parse_args() # Start a QGIS application without GUI qgs = QgsApplication([], False) qgs.initQgis() #project_path = args.project #output_folder = '/home/trolleway/tmp/tests' #layout_name = args.layout export_atlas(args.project, args.layout, args.output) # Close the QGIS application qgs.exitQgis()
def main(): # Start a QGIS application without GUI qgs = QgsApplication([], False) qgs.initQgis() sys.path.append('/usr/share/qgis/python/plugins') qgs.initQgis() project_path = '/home/osm2igeotopo/X_PROJET_OSM2IGEOTOPO25.qgs' output_folder = '/home/osm2igeotopo/data_temp/dalles_export/' layout_name = 'EXPORT_DALLE' print('Starter atlas export') export_atlas(project_path, layout_name, output_folder) # Close the QGIS application qgs.exitQgis()
class QgisSession: """ QGIS Session context manager """ def __init__(self): QgsApplication.setPrefixPath("/usr", True) gui_flag = False self.app = QgsApplication([], gui_flag) def __enter__(self): self.app.initQgis() # Disable WAL mode so that vector files don't get modified when read # https://github.com/qgis/QGIS/issues/23991 QSettings().setValue("/qgis/walForSqlite3", False) return self.app def __exit__(self, typ, value, traceback): self.app.exitQgis()
def buildmbtiles(project, minzoom, maxzoom, extend, outname): # Initialize QGIS os.environ["QT_QPA_PLATFORM"] = "offscreen" QgsApplication.setPrefixPath("/usr", True) qgs = QgsApplication([], False) qgs.initQgis() # Load project try: proj = QgsProject.instance() proj.read(project) except: logging.error(f"There was an error loading {project}") raise ValueError("Error loading QGIS project") # Initialize processing sys.path.append("/usr/share/qgis/python/plugins") import processing from processing.core.Processing import Processing Processing.initialize() # Call procedure params = { 'EXTENT': extend, 'ZOOM_MIN': minzoom, 'ZOOM_MAX': maxzoom, 'DPI': 96, 'BACKGROUND_COLOR': QColor(0, 0, 0, 0), 'TILE_FORMAT': 1, 'QUALITY': 75, 'METATILESIZE': 4, 'OUTPUT_FILE': outname } feedback = QgsProcessingFeedback() res = processing.run("qgis:tilesxyzmbtiles", params, feedback=feedback) # Clean up and return qgs.exitQgis() return res["OUTPUT_FILE"]
def main(argv): # create Qt application app = QtGui.QApplication(argv, True) # Set the app style # initialize qgis libraries QgsApplication.setPrefixPath(QGIS_PREFIX_PATH, True) QgsApplication.initQgis() # create main window wnd = MainWindow() wnd.show() # Start the app up retval = app.exec_() # We got an exit signal so time to clean up QgsApplication.exitQgis() sys.exit(retval)
def main(argv): names = [] for n in LAYERS: names.append(QString(n)) qgisPrefix = homeDir() QApplication.setOrganizationName("ICIMOD"); QApplication.setOrganizationDomain("icimod.org"); QApplication.setApplicationName("Glacial Lakes Viewer"); app = QApplication(argv, True) splash = SplashScreen(qgisPrefix) splash.showMessage(unicode("starting...")) QgsApplication.setPrefixPath(qgisPrefix, True) QgsApplication.initQgis() window = MainWindow(splash) window.mapCanvas.loadInitialLayers(splash) layers,rLayers = window.mapCanvas.getMapLayers(names) window.show() window.mapCanvas.refreshCanvas(splash,layers,rLayers) del splash app.exec_() QgsApplication.exitQgis()
def main(): # 实例化QGIS应用对象 qgs = QgsApplication([], True) qgs.setPrefixPath('qgis', True) # 启动QGIS qgs.initQgis() window = MapExplorer() window.show() exit_code = qgs.exec_() # 退出QGIS maskList = os.listdir('mask') sampleList = os.listdir('samples') if len(maskList) != 0 or len(sampleList) != 0: reply = QMessageBox.question(None, '提示', '是否删除已有样区?', QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: for file in maskList: path = os.path.join('mask', file) os.remove(path) for file in sampleList: path = os.path.join('samples', file) os.remove(path) qgs.exitQgis() sys.exit(exit_code)
def test(host, pguser): # create the test database os.system(f"dropdb --if-exists -h {host} -U {pguser} {wc_dbname}") os.system(f"createdb -h {host} -U {pguser} {wc_dbname}") os.system(f"dropdb --if-exists -h {host} -U {pguser} {dbname}") os.system(f"createdb -h {host} -U {pguser} {dbname}") qgs = QgsApplication([], False) qgs.initQgis() for test_class in [ SpatialitePluginTest, PgLocalPluginTest, PgServerPluginTest ]: test = test_class(host, pguser) test.test_checkout() del test test = test_class(host, pguser) test.test_checkout_w_selected_features() del test qgs.exitQgis()
def test(host, pguser): # create the test database os.system(f"dropdb --if-exists -h {host} -U {pguser} {wc_dbname}") os.system(f"createdb -h {host} -U {pguser} {wc_dbname}") os.system(f"dropdb --if-exists -h {host} -U {pguser} {dbname}") os.system(f"createdb -h {host} -U {pguser} {dbname}") qgs = QgsApplication([], False) qgs.initQgis() for test_class in [SpatialitePluginTest, PgLocalPluginTest, PgServerPluginTest]: test = test_class(host, pguser) test.test_checkout() del test test = test_class(host, pguser) test.test_checkout_w_selected_features() del test qgs.exitQgis()
def tearDownClass( self ): self.msg.show( "Info! TearDown started", 'info', True ) # test07 deletes the layer object, so create it again self.layer = QgsVectorLayer( self.layerPath, 'puntos', 'ogr' ) #Remove AutoField modified autoFieldId = self.autoFieldManager.buildAutoFieldId( self.layer, u'modified' ) self.autoFieldManager.removeAutoField( autoFieldId ) #Delete field f1 fieldIndex = self.layer.fieldNameIndex('f1') self.layer.dataProvider().deleteAttributes( [fieldIndex] ) self.layer.updateFields() #Delete features from test layer fIds = self.layer.allFeatureIds() self.layer.dataProvider().deleteFeatures( fIds ) #Remove layer from Registry QgsMapLayerRegistry.instance().removeMapLayer( self.layer.id() ) self.msg.show( "Info! TearDown finished", 'info', True ) QgsApplication.exitQgis()
def fin(): print ("teardown QGIS") QgsApplication.exitQgis()
def main(argv): import _winreg as wr licenseKey = None aReg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE) aKey = None try: targ = r'SOFTWARE\Microsoft\Windows\FlightPlannerLicense' print "*** Reading from", targ, "***" aKey = wr.OpenKey(aReg, targ) try: n, v, t = wr.EnumValue(aKey, 0) if n == "License": licenseKey = v print licenseKey except: print "no license" finally: try: wr.CloseKey(aKey) except: pass except: print "no License trag" finally: try: wr.CloseKey(aReg) except: pass app = QApplication(argv) QgsApplication.setPrefixPath(".", True) a = QgsApplication.initQgis() # f = file("D:/ccc.txt", "w") # ss = ["sfdffdsf", "233424324", "sdfsdfs"] # f.write("start") # f.writelines(ss) # f.close() print "File print End" licenceFlag = False if licenseKey != None: print "Compare Start" objValidate = Validate() print "aerodrome$pw3s$Pa$$W0rd" objValidate.secretPhase = "aerodrome$pw3s$Pa$$W0rd" # GlobalSettings objSetting = GlobalSettings.Load(Constants.globaleSettingsPath); objValidate.Key = String.QString2Str(QString(licenseKey)).replace( "-", "") print objValidate.Key # objValidate.Key = "IVAII-UTDIE-HGIEG-WMVOG" try: if (objValidate.IsValid and objValidate.IsOnRightMachine and objValidate.SetTime >= objValidate.DaysLeft ): # and objValidate.IsExpired == False ): licenceFlag = True except: pass print licenceFlag # if not licenceFlag: # dlgLicensing = DlgLicensing() # licenceFlag = dlgLicensing.exec_() # if licenceFlag: # print "Start MyWnd" define._appWidth = QApplication.desktop().screenGeometry().width() define._appHeight = QApplication.desktop().screenGeometry().height() window = MyWnd() window.setWindowState(Qt.WindowMaximized) window.show() retval = app.exec_() AirCraftOperation.g_AppSetting.WriteSettings() if retval: pass QgsApplication.exitQgis() sys.exit(retval)
def main(argv): import _winreg as windowsregistry licensekey = None localmachinekeyhandle = windowsregistry.ConnectRegistry(None, windowsregistry.HKEY_LOCAL_MACHINE) keyhandle = None try: keyargument = r'SOFTWARE\Microsoft\Windows\FlightPlannerLicense' print "*** Reading from", keyargument, "***" keyhandle = windowsregistry.OpenKey(localmachinekeyhandle, keyargument) try: n, v, t = windowsregistry.EnumValue(keyhandle, 0) if n == "License": licensekey = v print licensekey except: print "no license" finally: try: windowsregistry.CloseKey(keyhandle) except: pass except: print "no License trag" finally: try: windowsregistry.CloseKey(localmachinekeyhandle) except: pass # create QGis application app = QgsApplication(argv, True) QCoreApplication.setOrganizationName("IRSG") QCoreApplication.setOrganizationDomain("*****@*****.**") QCoreApplication.setApplicationName("FlightPlanner") # Initialize qgis libraries QgsApplication.setPrefixPath(".", True) QgsApplication.initQgis() licenceflag = False if licensekey is not None: print "Compare Start" objvalidate = Validate() print "aerodrome$pw3s$Pa$$W0rd" objvalidate.secretPhase = "aerodrome$pw3s$Pa$$W0rd" objvalidate.Key = String.QString2Str(QString(licensekey)).replace("-", "") print objvalidate.Key try: if objvalidate.IsValid and objvalidate.IsOnRightMachine and objvalidate.SetTime >= objvalidate.DaysLeft: # and objValidate.IsExpired == False ): licenceflag = True except: pass define._appWidth = QApplication.desktop().screenGeometry().width() define._appHeight = QApplication.desktop().screenGeometry().height() window = MyWnd() window.setWindowState(Qt.WindowMaximized) window.show() retval = app.exec_() AirCraftOperation.ApplicationSetting.WriteSettings() QgsApplication.exitQgis() sys.exit(retval)
def renderer(self): qgis = QgsApplication([], False) qgis.setPrefixPath(self.settings.get('path'), True) qgis.setMaxThreads(1) qgis.initQgis() while True: try: fndata, srs, render_size, extended, \ target_box, result = self.queue.get() layer = QgsVectorLayer(fndata, 'layer', 'ogr') crs = QgsCoordinateReferenceSystem(srs.id) layer.setCrs(crs) settings = QgsMapSettings() settings.setLayers([layer.id()]) settings.setFlag(QgsMapSettings.DrawLabeling) settings.setFlag(QgsMapSettings.Antialiasing) settings.setCrsTransformEnabled(True) settings.setDestinationCrs(crs) settings.setMapUnits(crs.mapUnits()) settings.setOutputSize(QSize(*render_size)) settings.setExtent(QgsRectangle(*extended)) settings.setOutputImageFormat(QImage.Format_ARGB32) bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0)) settings.setBackgroundColor(bgcolor) settings.setOutputDpi(96) QgsMapLayerRegistry.instance().addMapLayer(layer) settings.setLayers([layer.id()]) # Создаем QImage руками чтобы можно было использовать # QgsMapRendererCustomPainterJob. Остальные не позволяют # обойти баг с рисованием поверх старого. img = QImage(settings.outputSize(), QImage.Format_ARGB32) # Эти костыли нужны для того, чтобы корректно рисовались # слои на прозрачном фоне, без этого получается каша. img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255))) img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0))) # DPI должно быть таким же как в settings, иначе ошибка. В QImage # разрешение указывается в точках на метр по каждой оси. dpm = settings.outputDpi() / 25.4 * 1000 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) painter = QPainter(img) job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() # Преобразование QImage в PIL ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) img = PIL.Image.open(buf) # Вырезаем нужный нам кусок изображения result.put(img.crop(target_box)) except Exception as e: self.logger.error(e.message) qgis.exitQgis()
from processing.core.Processing import Processing Processing.initialize() import OTBSpecific_XMLcreation # try: # import processing # except ImportError, e: # raise Exception("Processing must be installed and available in PYTHONPATH") try: import otbApplication except ImportError as e: raise Exception("OTB python plugins must be installed and available in PYTHONPATH") create_xml_descriptors() create_html_description() #Check if some application are not listed in the white/black list logger = get_OTB_log() white_list = get_white_list() black_list = get_black_list() for available_app in otbApplication.Registry.GetAvailableApplications(): try: if available_app not in white_list and available_app not in black_list: logger.error("Application " + available_app + " is not listed in white_list.xml or black_list.xml. Need to be fix.") except Exception: logger.error(traceback.format_exc()) # Exit applications QgsApplication.exitQgis()
def on_quit(): QgsApplication.exitQgis() app.quit()
def exit(self): from qgis.core import QgsApplication QgsApplication.exitQgis() QgsApplication.quit()
def main( argv ): print 'I: Starting viewer ...' app = SingletonApp( argv ) dictOpts = { '-h':'', '-p':'5432', '-U':'', '-W':'', '-d':'', '-s':'public', '-t':'', '-g':'', 'type':'unknown', 'srid':'', 'col':'' } opts, args = getopt.getopt( sys.argv[1:], 'h:p:U:W:d:s:t:g:', [] ) dictOpts.update( opts ) if dictOpts['-t'] == '': print >> sys.stderr, 'E: Table name is required' print __doc__ sys.exit( 1 ) d = QSqlDatabase.addDatabase( "QPSQL", "PgSQLDb" ) d.setHostName( dictOpts['-h'] ) d.setPort( int( dictOpts['-p'] ) ) d.setDatabaseName( dictOpts['-d'] ) d.setUserName( dictOpts['-U'] ) d.setPassword( dictOpts['-W'] ) if d.open(): print 'I: Database connection was succesfull' query = QSqlQuery( d ) query.exec_( "SELECT Count(srid) FROM raster_columns WHERE r_table_schema = '%s' AND r_table_name = '%s'" % ( dictOpts['-s'], dictOpts['-t'] ) ) if query.next() and query.value( 0 ).toBool(): # Raster layer (WKTRaster)! query.exec_( "SELECT srid, r_raster_column FROM raster_columns \ WHERE r_table_schema = '%s' AND \ r_table_name = '%s' " % ( dictOpts['-s'], dictOpts['-t'] ) ) if query.next(): dictOpts[ 'srid' ] = str( query.value( 0 ).toString() ) dictOpts[ 'col' ] = str( query.value( 1 ).toString() ) dictOpts['type'] = 'raster' print 'I: Raster layer detected' else: # Vector layer? query.exec_( "SELECT column_name FROM information_schema.columns \ WHERE table_schema = '%s' AND \ table_name = '%s' AND \ udt_name = 'geometry' LIMIT 1" % ( dictOpts['-s'], dictOpts['-t'] ) ) if not query.next(): # Geography layer? query.exec_( "SELECT column_name FROM information_schema.columns \ WHERE table_schema = '%s' AND \ table_name = '%s' AND \ udt_name = 'geography' LIMIT 1" % ( dictOpts['-s'], dictOpts['-t'] ) ) if query.first(): # Vector layer! dictOpts[ '-g' ] = str( query.value( 0 ).toString() ) query.exec_( "SELECT srid FROM geometry_columns \ WHERE f_table_schema = '%s' AND \ f_table_name = '%s' " % ( dictOpts['-s'], dictOpts['-t'] ) ) if query.next(): dictOpts[ 'srid' ] = str( query.value( 0 ).toString() ) dictOpts['type'] = 'vector' print 'I: Vector layer detected' if not dictOpts[ 'type' ] == 'unknown': # The object is a layer if app.is_running: # Application already running, send message to load data app.send_message( dictOpts ) else: # Start the Viewer # QGIS libs init QgsApplication.setPrefixPath(qgis_prefix, True) QgsApplication.initQgis() # Open viewer wnd = ViewerWnd( app, dictOpts ) wnd.move(100,100) wnd.resize(400, 500) wnd.show() retval = app.exec_() # Exit QgsApplication.exitQgis() print 'I: Exiting ...' sys.exit(retval) else: show_error("Error when opening layer", "Layer '%s.%s' doesn't exist. Be sure the selected object is either raster or vector layer." % (dictOpts['-s'], dictOpts['-t'])) else: show_error("Connection error", "Error when connecting to database.")
QgsMapLayerRegistry.instance().addMapLayers([layer]) layer.setGrayBandName(layer.bandName(1)) layer.setDrawingStyle(QgsRasterLayer.SingleBandPseudoColor) layer.setColorShadingAlgorithm(QgsRasterLayer.PseudoColorShader) layer.saveDefaultStyle() self.widget.zoomToFullExtent() print self.widget.extent().toString() print layer.extent().toString() self.widget.refresh() if __name__ == "__main__": gui_flag = True # our app has a gui app = QgsApplication(sys.argv, gui_flag) # Note: This block is not needed for QGIS > 1.8 which will # automatically check the QGIS_PREFIX_PATH var so it is here # for backwards compatibility only #if 'QGIS_PREFIX_PATH' in os.environ: # myPath = os.environ['QGIS_PREFIX_PATH'] #else: # myPath = '/Applications/QGIS.app/contents/MacOS' # True == check our path for providers #app.setPrefixPath(myPath, True) app.initQgis() print app.showSettings() for item in QgsProviderRegistry.instance().providerList(): print str(item) dialog = Dialog() app.exec_() app.exitQgis()
def main(argv): print "I: Starting viewer ..." app = SingletonApp(argv) dictOpts = { "-h": "", "-p": "5432", "-U": "", "-W": "", "-d": "", "-s": "public", "-t": "", "-g": "", "type": "unknown", "srid": "", } opts, args = getopt.getopt(sys.argv[1:], "h:p:U:W:d:s:t:g:", []) dictOpts.update(opts) if dictOpts["-t"] == "": print >> sys.stderr, "E: Table name is required" print __doc__ sys.exit(1) d = QSqlDatabase.addDatabase("QPSQL", "PgSQLDb") d.setHostName(dictOpts["-h"]) d.setPort(int(dictOpts["-p"])) d.setDatabaseName(dictOpts["-d"]) d.setUserName(dictOpts["-U"]) d.setPassword(dictOpts["-W"]) if d.open(): print "I: Database connection was succesfull" query = QSqlQuery(d) query.exec_( "SELECT Count(oid) FROM raster_columns WHERE r_table_schema = '%s' AND r_table_name = '%s'" % (dictOpts["-s"], dictOpts["-t"]) ) if query.next() and query.value(0).toBool(): # Raster layer (WKTRaster)! query.exec_( "SELECT srid FROM raster_columns \ WHERE r_table_schema = '%s' AND \ r_table_name = '%s' " % (dictOpts["-s"], dictOpts["-t"]) ) if query.next(): dictOpts["srid"] = str(query.value(0).toString()) dictOpts["type"] = "raster" print "I: Raster layer detected" else: # Vector layer? query.exec_( "SELECT column_name FROM information_schema.columns \ WHERE table_schema = '%s' AND \ table_name = '%s' AND \ udt_name = 'geometry' LIMIT 1" % (dictOpts["-s"], dictOpts["-t"]) ) if query.next(): # Vector layer! dictOpts["-g"] = str(query.value(0).toString()) query.exec_( "SELECT srid FROM geometry_columns \ WHERE f_table_schema = '%s' AND \ f_table_name = '%s' " % (dictOpts["-s"], dictOpts["-t"]) ) if query.next(): dictOpts["srid"] = str(query.value(0).toString()) dictOpts["type"] = "vector" print "I: Vector layer detected" if not dictOpts["type"] == "unknown": # The object is a layer if app.is_running: # Application already running, send message to load data app.send_message(dictOpts) else: # Start the Viewer # QGIS libs init QgsApplication.setPrefixPath(qgis_prefix, True) QgsApplication.initQgis() # Open viewer wnd = ViewerWnd(app, dictOpts) wnd.move(100, 100) wnd.resize(400, 500) wnd.show() retval = app.exec_() # Exit QgsApplication.exitQgis() print "I: Exiting ..." sys.exit(retval) else: show_error( "Error when opening layer", "Layer '%s.%s' doesn't exist. Be sure the selected object is either raster or vector layer." % (dictOpts["-s"], dictOpts["-t"]), ) else: show_error("Connection error", "Error when connecting to database.")
if __name__ == "__main__": outputImageName = "multipatch." + str( os.environ['__VJ_INTERMEDIATE_GRAPHICS_FORMAT__']) print "initQgis" qgishome = "/usr" QgsApplication.setPrefixPath(qgishome, True) QgsApplication.initQgis() print QgsApplication.showSettings() print " ...Done" load_layers() style = 'templatestyle.qml' print "Set style:", style for layer in QgsMapLayerRegistry.instance().mapLayers().values(): layer.loadNamedStyle(style) print " ...Done" # Render all loaded layers (works with project files to) resolution = os.environ["__VJ_RESOLUTION_HEIGHTMAP__"] renderLayers(int(resolution), QgsMapLayerRegistry.instance().mapLayers(), "./out/" + outputImageName) print "exit" QgsApplication.exitQgis()
qgs_server.putenv('SERVER_NAME', self.server.server_name) qgs_server.putenv('REQUEST_URI', self.path) parsed_path = urllib.parse.urlparse(self.path) headers, body = qgs_server.handleRequest(parsed_path.query) headers_dict = dict(h.split(': ', 1) for h in headers.decode().split('\n') if h) try: self.send_response(int(headers_dict['Status'].split(' ')[0])) except: self.send_response(200) for k, v in list(headers_dict.items()): self.send_header(k, v) self.end_headers() self.wfile.write(body) return def do_POST(self): content_len = int(self.headers.get('content-length', 0)) post_body = self.rfile.read(content_len).decode() request = post_body[1:post_body.find(' ')] self.path = self.path + '&REQUEST_BODY=' + \ post_body.replace('&', '') + '&REQUEST=' + request return self.do_GET() if __name__ == '__main__': server = HTTPServer(('localhost', QGIS_SERVER_DEFAULT_PORT), Handler) print('Starting server on localhost:%s, use <Ctrl-C> to stop' % QGIS_SERVER_DEFAULT_PORT) server.serve_forever() qgs_app.exitQgis()
def close(self): # Exit applications QgsApplication.exitQgis() QgsApplication.exit()
def renderer(self): if 'QGIS_AUTH_DB_DIR_PATH' not in os.environ: os.environ['QGIS_AUTH_DB_DIR_PATH'] = '/tmp' qgis = None while True: options, result = self.queue.get() # Don't start QGIS until first request if qgis is None: qgis = QgsApplication([], False) qgis.setPrefixPath(self.settings.get('path'), True) qgis.setDefaultSvgPaths(qgis.svgPaths() + self.settings.get('svgpaths')) qgis.setMaxThreads(1) qgis.initQgis() try: if isinstance(options, LegendOptions): style, = options layer = self._qgs_memory_layer(style) layer.setName(style.parent.display_name) QgsMapLayerRegistry.instance().addMapLayer(layer) root = QgsLayerTreeGroup() root.addLayer(layer) # 'Cannot create a QPixmap when no GUI is being used' # warning occurs here model = QgsLayerTreeModel(root) settings = QgsLegendSettings() settings.setTitle('') settings.setBoxSpace(1) settings.setSymbolSize(QSizeF(5, 3)) settings.setDpi(96) renderer = QgsLegendRenderer(model, settings) # Dots per mm dpmm = settings.dpi() / 25.4 min_size = renderer.minimumSize() size = QSize(dpmm * min_size.width(), dpmm * min_size.height()) img = QImage(size, QImage.Format_ARGB32) img.fill(QColor(0, 0, 0, 0)) painter = QPainter() painter.begin(img) painter.scale(dpmm, dpmm) renderer.drawLegend(painter) painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) result.put(buf) else: path = features = None if isinstance(options, VectorRenderOptions): style, features, render_size, \ extended, target_box = options layer = self._qgs_memory_layer(style, features=features) elif isinstance(options, RasterRenderOptions): style, path, render_size, \ extended, target_box = options layer = QgsRasterLayer(path) layer.loadNamedStyle( self.env.file_storage.filename(style.qml_fileobj)) settings = QgsMapSettings() settings.setLayers([layer.id()]) settings.setFlag(QgsMapSettings.DrawLabeling) settings.setFlag(QgsMapSettings.Antialiasing) settings.setCrsTransformEnabled(True) settings.setDestinationCrs(layer.crs()) settings.setMapUnits(layer.crs().mapUnits()) settings.setOutputSize(QSize(*render_size)) settings.setExtent(QgsRectangle(*extended)) settings.setOutputImageFormat(QImage.Format_ARGB32) bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0)) settings.setBackgroundColor(bgcolor) settings.setOutputDpi(96) QgsMapLayerRegistry.instance().addMapLayer(layer) settings.setLayers([layer.id()]) # Create QImage by hand to be able to use # QgsMapRendererCustomPainterJob. Others will not # allow to workaround a bug with overlay rendering. img = QImage(settings.outputSize(), QImage.Format_ARGB32) # These cludges are needed for rendering # on transparent background, otherwise it's a mess. img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255))) img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0))) # DPI should be equal to settings, otherwise an error. # In QImage the resolution is set in dots per meter # for each axis. dpm = settings.outputDpi() / 25.4 * 1000 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) painter = QPainter(img) job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() img = self._qimage_to_pil(img) # Clip needed part result.put(img.crop(target_box)) # Cleanup if path is not None: gdal.Unlink(path) except Exception as exc: self.logger.error(exc.message) result.put(exc) qgis.exitQgis()
def exit(self): sys.excepthook = self._oldhook from qgis.core import QgsApplication QgsApplication.exitQgis() QgsApplication.quit()
self.mapCanvas.refresh() # self.set_crs() def set_crs(self): self.moveThread = MoveThread(self) self.moveThread.degreeSignal.connect(self.process_signal) self.moveThread.start() def process_signal(self, d): print(d) crsDest = QgsCoordinateReferenceSystem( f"PROJ:+proj=ortho +lat_0=0 +lon_0={d} +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs" ) self.mapCanvas.setDestinationCrs(crsDest) self.mapCanvas.refresh() if __name__ == '__main__': qgsAPP = QgsApplication([], True) QgsApplication.setPrefixPath("qgis", True) qgsAPP.initQgis() myApp = MyApp() myApp.show() qgsAPP.exec_() qgsAPP.exitQgis()
def exit(self): sys.excepthook = self._oldhook from qgis.core import QgsApplication QgsApplication.exitQgis() QgsApplication.quit()
def main_function(tif_file_name, output_file_name, input_directory=INPUT_DIRECTORY, output_directory=OUTPUT_DIRECTORY): """The main function to calculate NDVI from tif file in `tif_path` to `output_path` """ full_tif_path = os.path.join(input_directory, tif_file_name) full_output_path = os.path.join(output_directory, output_file_name) if not os.path.exists(full_tif_path): print('TIF file %s is not exist' % full_tif_path) else: print('TIF file %s is exist' % full_tif_path) #### Prepare QGIS #### import sys import qgis.utils from qgis.core import (QgsApplication, QgsProcessingFeedback, QgsVectorLayer, QgsProcessingProvider, QgsProcessingRegistry, QgsRasterLayer, QgsProject) from qgis.analysis import QgsNativeAlgorithms # See https://gis.stackexchange.com/a/155852/4972 for details about the prefix QgsApplication.setPrefixPath('/usr', True) qgs = QgsApplication([], False) qgs.initQgis() # # Append the path where processing plugin can be found sys.path.append('/usr/share/qgis/python/plugins/') import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) #### Add NDVI Provider #### provider = NDVIProvider() provider.loadAlgorithms() QgsApplication.processingRegistry().addProvider(provider) #### Run split bands algorithm #### # algorithm id: split_band_algorithm_id = 'uas:Split_bands' # parameters split_band_algorithm_parameters = { 'inputimage': full_tif_path, 'Red': os.path.join(TEMP_DIRECTORY, 'red.sdat'), 'Green': os.path.join(TEMP_DIRECTORY, 'green.sdat'), 'Blue': os.path.join(TEMP_DIRECTORY, 'nir.sdat'), 'R_conv': os.path.join(OUTPUT_DIRECTORY, 'red_conv.tif'), 'G_conv': os.path.join(OUTPUT_DIRECTORY, 'green_conv.tif'), 'B_conv': os.path.join(OUTPUT_DIRECTORY, 'nir_conv.tif'), } # Run algorithm split_band_result = processing.run(split_band_algorithm_id, split_band_algorithm_parameters) # Check result print('Path of G_conv: %s is exist = %s' % (split_band_result.get('G_conv'), os.path.exists(split_band_result.get('G_conv')))) print('Path of R_conv: %s is exist = %s' % (split_band_result.get('R_conv'), os.path.exists(split_band_result.get('R_conv')))) #### Run NDVI raster calculation algorithm #### # algorithm id: ndvi_algorithm_id = 'uas:Calculate_NDVI' # parameters ndvi_algorithm_parameters = { 'inputnirband': split_band_result['B_conv'], 'inputredband': split_band_result['R_conv'], 'Output': full_output_path } if False: # Run algorithm ndvi_result = processing.run(ndvi_algorithm_id, ndvi_algorithm_parameters) # Check result print('Path of NDVI: %s is exist = %s' % (ndvi_result.get('Output'), os.path.exists(ndvi_result.get('Output')))) else: from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry entries = [] nir_layer = QgsRasterLayer(ndvi_algorithm_parameters['inputnirband'], "nir") QgsProject.instance().addMapLayer(nir_layer) nir = QgsRasterCalculatorEntry() nir.ref = 'nir@1' nir.raster = nir_layer nir.bandNumber = 1 entries.append(nir) red_layer = QgsRasterLayer(ndvi_algorithm_parameters['inputredband'], "red") QgsProject.instance().addMapLayer(red_layer) red = QgsRasterCalculatorEntry() red.ref = 'red@1' red.raster = red_layer red.bandNumber = 1 entries.append(red) ndvi_expression = 'Float( nir@1 - red@1 ) / Float( nir@1 + red@1 )' calc = QgsRasterCalculator(ndvi_expression, ndvi_algorithm_parameters['Output'], 'GTiff', nir_layer.extent(), nir_layer.width(), nir_layer.height(), entries) a = calc.processCalculation() print('Result: ', a) # Exit QGIS qgs.exitQgis()
print('Raster layer failed to load') if not layer_polygon.isValid(): print('Polygon layer failed to load') # Create a zonal statistics object, automatically saved to file band = 1 # raster band with the data we are after zonalstats = QgsZonalStatistics( layer_polygon, # shapefile layer_raster, # .tif 'elev_', # prefix for the new column added to the shapefile band, # raster band we're interested in stats=QgsZonalStatistics.Mean).calculateStatistics(None) # Clean memory qgs.exitQgis() # --- Code provenance # Generates a basic log file in the domain folder and copies the control file and itself there. # Set the log path and file name logPath = intersect_path log_suffix = '_catchment_dem_intersect_log.txt' # Create a log folder logFolder = '_workflow_log' Path(logPath / logFolder).mkdir(parents=True, exist_ok=True) # Copy this script thisFile = '1_find_HRU_elevation.py' copyfile(thisFile, logPath / logFolder / thisFile)
# Quantos campos qtd_campos = len(subCamada.fields()) print(f"Quantidade de campos = {qtd_campos}") # Tipo de geometria tp_geometria = QgsWkbTypes.displayString(subCamada.wkbType()) print(f"Geometria = {tp_geometria}") # SRC subSrc = subCamada.crs().authid() print(f"SRC = {subSrc}") metadado += f"\n\nNome Camada: {nome}" metadado += "\nTotal de Feições: {0}".format(qt_feicoes) metadado += "\nQuantidade de Campos: %d" % (qtd_campos) metadado += f"\nGeometria: {tp_geometria}" metadado += f"\nSRC: {subSrc}" else: print('Seu caminho tem algo errado!!!') nomeMetadado = arquivoFisico.split('.')[0] + "_METADADOS.txt" caminhoMetadado = path.join(diretorio, nomeMetadado) with open(caminhoMetadado, 'w') as meta: meta.write(metadado) print('Metadado Criado Lindamente!') #print(caminhoMetadado) qgis.exitQgis()
app = QgsApplication([bytes(x, "utf8") for x in sys.argv], True) app.initQgis() # feature example layer = QgsVectorLayer("None?field=y:double", "test_feature", "memory") feature = QgsFeature() y_values = ",".join([str(random.uniform(1., 100.)) for i in range(1000)]) feature.setAttributes([y_values]) feature.setFeatureId(1) layer.dataProvider().addFeatures([feature]) x_values = [float(x) for x in range(1, 1001)] layer2 = QgsVectorLayer("None?field=y:double", "test_feature", "memory") feature = QgsFeature() y_values2 = ",".join([str(random.uniform(1., 100.)) for i in range(1000)]) feature.setAttributes([y_values2]) feature.setFeatureId(1) layer2.dataProvider().addFeatures([feature]) w = TimeSeriesView("Sample") w.add_data_row( FeatureData(layer, "y", feature_id=1, x_start=1.0, x_delta=1.0), "test title", "m") w.add_data_row(FeatureData(layer2, "y", x_values, 1), "test title2", "m") w.show() app.exec_() app.exitQgis()
def handler(event, context): # get events passed into lambda via string like this: # { # "maxX": "0", # "maxY": "85.051128514163", # "minX": "0", # "minY": "-179.999996920672", # "zoomLevel": "1", # "imageBucket": "data.southfact.com", # "imageFile": "current-year-to-date/swirLatestChangeL8CONUS.tif", # "styleBucket": "data.southfact.com", # "styleFile": "qgis-styles-for-tile-creation/SWIR_SOUTHFACT_nodata_0.qml", # "tileBucket": "tiles.southfact.com", # "tileFolder": "latest_change_SWIR_L8" # } # aws source based on AWS s3 folder/image.tif imageBucket = event['imageBucket'] imageFile = event['imageFile'] imageSource = imageBucket + '/' + imageFile # the bounds of minX etc should be in WGS84 lat long and should be a bounds of # equal to zoom level 7 box. the ideas is that the function will take in as argument a # the bounds for the entire tiled area so it can do it all at once in lambda # for southfact that is about 69 squares/processes once a day + one that does zoom-level 1-6 minX = event['minX'] maxX = event['maxX'] minY = event['minY'] maxY = event['maxY'] #QGis style bucket, folder/filename.qml # of the options this is valid style file styleBucket = event['styleBucket'] styleFile = event['styleFile'] #tile cache bucket and folder tileBucket = event['tileBucket'] tileFolder = event['tileFolder'] # zoom level to process zoomLevel = event['zoomLevel'] # get arguments for tile extString = str(minX) + ',' + str(maxX) + ',' + str(minY) + ',' + str(maxY) # this will always be temp and then will aws sync to s3 OutputTileDirectory = '/tmp/cache' if not os.path.exists(OutputTileDirectory): os.mkdir(OutputTileDirectory) arg = { 'extString': extString, 'zoomLevel': zoomLevel, 'OutputTileDirectory': OutputTileDirectory, 'tileBucket': tileBucket, 'tileFolder': tileFolder } # so more can be done at the same time qgisStylePath = '/tmp/qgisstyle.qml' s3 = boto3.client('s3') s3.download_file(styleBucket, styleFile, qgisStylePath) imageForTiles = clipSource(imageSource, minX, maxX, minY, maxY) rasterTileLayer = addRaster(imageForTiles) rasterCRS = rasterTileLayer.crs() # only process is projection is valid if rasterCRS.isValid(): # setup enviroment for qgis map setupEnviroment(rasterTileLayer) addStyle(qgisStylePath, rasterTileLayer) createTiles(arg) else: print( "The raster does not have a valid projection, its likely you created it with software that created a custom or vendor specific projection. You shoould try reprojecting the image with gdal, gdalwarp to a defined proj4 projection, the site http://spatialreference.org/ref/epsg/3031/ can help find the correct and known EPSG code." ) QgsApplication.exitQgis() end_time = time.time() print("Took %s to create the tiles." % (convert(end_time - start_time))) return 0
#!/usr/bin/env python3 from qgis.core import QgsApplication from dialog import ApplicationDialog QgsApplication.setPrefixPath('/home/etienne/dev/app/local/', True) application = QgsApplication([], True) application.initQgis() dialog = ApplicationDialog(application) application.exitQgis()
def main(argv): print 'I: Starting viewer ...' app = SingletonApp(argv) dictOpts = { '-h': '', '-p': '5432', '-U': '', '-W': '', '-d': '', '-s': 'public', '-t': '', '-g': '', 'type': 'unknown', 'srid': '', 'col': '' } opts, args = getopt.getopt(sys.argv[1:], 'h:p:U:W:d:s:t:g:', []) dictOpts.update(opts) if dictOpts['-t'] == '': print >> sys.stderr, 'E: Table name is required' print __doc__ sys.exit(1) d = QSqlDatabase.addDatabase("QPSQL", "PgSQLDb") d.setHostName(dictOpts['-h']) d.setPort(int(dictOpts['-p'])) d.setDatabaseName(dictOpts['-d']) d.setUserName(dictOpts['-U']) d.setPassword(dictOpts['-W']) if d.open(): print 'I: Database connection was succesfull' query = QSqlQuery(d) query.exec_( "SELECT Count(srid) FROM raster_columns WHERE r_table_schema = '%s' AND r_table_name = '%s'" % (dictOpts['-s'], dictOpts['-t'])) if query.next() and query.value( 0).toBool(): # Raster layer (WKTRaster)! query.exec_("SELECT srid, r_raster_column FROM raster_columns \ WHERE r_table_schema = '%s' AND \ r_table_name = '%s' " % (dictOpts['-s'], dictOpts['-t'])) if query.next(): dictOpts['srid'] = str(query.value(0).toString()) dictOpts['col'] = str(query.value(1).toString()) dictOpts['type'] = 'raster' print 'I: Raster layer detected' else: # Vector layer? query.exec_("SELECT column_name FROM information_schema.columns \ WHERE table_schema = '%s' AND \ table_name = '%s' AND \ udt_name = 'geometry' LIMIT 1" % (dictOpts['-s'], dictOpts['-t'])) if not query.next(): # Geography layer? query.exec_( "SELECT column_name FROM information_schema.columns \ WHERE table_schema = '%s' AND \ table_name = '%s' AND \ udt_name = 'geography' LIMIT 1" % (dictOpts['-s'], dictOpts['-t'])) if query.first(): # Vector layer! dictOpts['-g'] = str(query.value(0).toString()) query.exec_("SELECT srid FROM geometry_columns \ WHERE f_table_schema = '%s' AND \ f_table_name = '%s' " % (dictOpts['-s'], dictOpts['-t'])) if query.next(): dictOpts['srid'] = str(query.value(0).toString()) dictOpts['type'] = 'vector' print 'I: Vector layer detected' if not dictOpts['type'] == 'unknown': # The object is a layer if app.is_running: # Application already running, send message to load data app.send_message(dictOpts) else: # Start the Viewer # QGIS libs init QgsApplication.setPrefixPath(qgis_prefix, True) QgsApplication.initQgis() # Open viewer wnd = ViewerWnd(app, dictOpts) wnd.move(100, 100) wnd.resize(400, 500) wnd.show() retval = app.exec_() # Exit QgsApplication.exitQgis() print 'I: Exiting ...' sys.exit(retval) else: show_error( "Error when opening layer", "Layer '%s.%s' doesn't exist. Be sure the selected object is either raster or vector layer." % (dictOpts['-s'], dictOpts['-t'])) else: show_error("Connection error", "Error when connecting to database.")