class RoamApp(object): def __init__(self, sysargv, apppath, prefixpath, settingspath, libspath, i18npath): self.sysargv = sysargv self.apppath = apppath self.prefixpath = prefixpath self.settingspath = settingspath self.libspath = libspath self.i18npath = i18npath self.app = None self.translationFile = None def init(self): from qgis.core import QgsApplication from PyQt4.QtGui import QApplication, QFont from PyQt4.QtCore import QLocale, QTranslator try: import PyQt4.QtSql except ImportError: pass self.app = QgsApplication(self.sysargv, True) QgsApplication.setPrefixPath(self.prefixpath, True) QgsApplication.initQgis() locale = QLocale.system().name() self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale)) translator = QTranslator() translator.load(self.translationFile, "i18n") self.app.installTranslator(translator) QApplication.setStyle("Plastique") QApplication.setFont(QFont('Segoe UI')) return self def exec_(self): self.app.exec_() def exit(self): from qgis.core import QgsApplication QgsApplication.exitQgis() QgsApplication.quit() def setActiveWindow(self, widget): self.app.setActiveWindow(widget) def dump_configinfo(self): from qgis.core import QgsApplication, QgsProviderRegistry from PyQt4.QtGui import QImageReader, QImageWriter yield QgsProviderRegistry.instance().pluginList() yield QImageReader.supportedImageFormats() yield QImageWriter.supportedImageFormats() yield QgsApplication.libraryPaths() yield "Translation file: {}".format(self.translationFile)
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(): 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(): # 实例化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)
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 save(self): with open(self.path, 'w') as f: yaml.dump(data=self.settings, stream=f, default_flow_style=False) settings = Settings(settingspath) settings.load() window = MainWindow(settings=settings) sys.excepthook = partial(excepthook, window.raiseerror) try: projectpath = sys.argv[1] except IndexError: projectpath = os.path.join(os.getcwd(), "projects") sys.path.append(projectpath) projects = roam.project.getProjects(projectpath) window.loadprojects(projects) window.actionProject.toggle() window.viewprojects() window.updateUIState(1) window.show() roam.utils.info("Roam Loaded in {}".format(str(time.time() - start))) app.exec_() QgsApplication.exitQgis() sys.exit()
class RoamApp(object): def __init__(self, sysargv, apppath, prefixpath, settingspath, libspath, i18npath, projectsroot): self.sysargv = sysargv self.apppath = apppath self.prefixpath = prefixpath self.settingspath = settingspath self.libspath = libspath self.i18npath = i18npath self.app = None self.translationFile = None self.projectsroot = projectsroot self._oldhook = sys.excepthook def init(self, logo, title): from qgis.core import QgsApplication from PyQt4.QtGui import QApplication, QFont, QIcon from PyQt4.QtCore import QLocale, QTranslator try: import PyQt4.QtSql except ImportError: pass self.app = QgsApplication(self.sysargv, True) import roam.roam_style self.app.setStyleSheet(roam.roam_style.appstyle) QgsApplication.setPrefixPath(self.prefixpath, True) QgsApplication.initQgis() locale = QLocale.system().name() self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale)) translator = QTranslator() translator.load(self.translationFile, "i18n") self.app.installTranslator(translator) QApplication.setStyle("Plastique") QApplication.setFont(QFont('Segoe UI')) QApplication.setWindowIcon(QIcon(logo)) QApplication.setApplicationName(title) import roam.editorwidgets.core roam.editorwidgets.core.registerallwidgets() return self def set_error_handler(self, errorhandler, logger): sys.excepthook = functools.partial(self.excepthook, errorhandler) self.logger = logger def excepthook(self, errorhandler, exctype, value, traceback): self.logger.error("Uncaught exception", exc_info=(exctype, value, traceback)) errorhandler(exctype, value, traceback) def exec_(self): self.app.exec_() def exit(self): sys.excepthook = self._oldhook from qgis.core import QgsApplication QgsApplication.exitQgis() QgsApplication.quit() def setActiveWindow(self, widget): self.app.setActiveWindow(widget) def dump_configinfo(self): from qgis.core import QgsApplication, QgsProviderRegistry from PyQt4.QtGui import QImageReader, QImageWriter import roam from qgis.core import QGis config = [] config.append("====Providers===") config.append(QgsProviderRegistry.instance().pluginList()) config.append("====Library paths===") config.append('\n'.join(QgsApplication.libraryPaths())) config.append("====Translation File===") config.append(self.translationFile) config.append("Roam Version: {}".format(roam.__version__)) config.append("QGIS Version: {}".format(str(QGis.QGIS_VERSION))) return '\n'.join(config)
class RoamApp(object): def __init__(self, sysargv, apppath, prefixpath, settingspath, libspath, i18npath, projectsroot): self.sysargv = sysargv self.apppath = apppath self.prefixpath = prefixpath self.settingspath = settingspath self.approot = apppath self.profileroot = apppath self.libspath = libspath self.i18npath = i18npath self.app = None self.translationFile = None self.projectsroot = projectsroot self._oldhook = sys.excepthook self.sourcerun = False self.config = None def init(self, logo, title, **kwargs): from qgis.core import QgsApplication from qgis.PyQt.QtWidgets import QApplication from qgis.PyQt.QtGui import QFont, QIcon from qgis.PyQt.QtCore import QLocale, QTranslator try: import qgis.PyQt.QtSql except ImportError: pass # In python3 we need to convert to a bytes object (or should # QgsApplication accept a QString instead of const char* ?) try: argvb = list(map(os.fsencode, sys.argv)) except AttributeError: argvb = sys.argv self.app = QgsApplication(argvb, True) QgsApplication.setPrefixPath(self.prefixpath, True) QgsApplication.initQgis() locale = QLocale.system().name() self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale)) translator = QTranslator() translator.load(self.translationFile, "i18n") self.app.installTranslator(translator) QApplication.setStyle("Plastique") QApplication.setFont(QFont('Segoe UI')) QApplication.setWindowIcon(QIcon(logo)) QApplication.setApplicationName(title) import roam.editorwidgets.core if "register_widgets" not in kwargs: register_widgets = True else: register_widgets = False if register_widgets: roam.editorwidgets.core.registerallwidgets() import roam.qgisfunctions return self @property def data_folder(self): return os.path.join(self.projectsroot, "_data") def set_error_handler(self, errorhandler, logger): sys.excepthook = functools.partial(self.excepthook, errorhandler) self.logger = logger def excepthook(self, errorhandler, exctype, value, traceback): self.logger.error("Uncaught exception", exc_info=(exctype, value, traceback)) errorhandler(exctype, value, traceback) def exec_(self): self.app.exec_() def exit(self): sys.excepthook = self._oldhook from qgis.core import QgsApplication QgsApplication.exitQgis() QgsApplication.quit() def setActiveWindow(self, widget): self.app.setActiveWindow(widget) def dump_configinfo(self): from qgis.core import QgsApplication, QgsProviderRegistry import roam from qgis.core import Qgis config = [] config.append("====Providers===") config.append(QgsProviderRegistry.instance().pluginList()) config.append("====Library paths===") config.append('\n'.join(QgsApplication.libraryPaths())) config.append("====Translation File===") config.append(self.translationFile) config.append("Roam Version: {}".format(roam.__version__)) config.append(u"QGIS Version: {}".format(str(Qgis.QGIS_VERSION))) return '\n'.join(config)
# -*- coding: utf-8 -*- # @Author : llc # @Time : 2020/4/19 16:23 from qgis.core import QgsApplication from splash import SplashScreen from widgets.main import MainWindow from config import setup_env setup_env() # 创建对QgsApplication的引用,第二个参数设置为False将禁用GUI qgs = QgsApplication([], True) # 启动画面 splash = SplashScreen() splash.show() # 提供qgis安装位置的路径(windows默认:C:\Program Files\QGIS 3.4\apps\qgis-ltr) qgs.setPrefixPath("qgis", True) # 初始化 qgs.initQgis() # 主窗口 mainWindow = MainWindow() splash.finish(mainWindow) mainWindow.show() # 脚本完成后,调用exitQgis()从内存中删除提供者和图层注册 qgs.exec_() qgs.exitQgis()
from qgis.core import QgsApplication from PyQt5.QtWidgets import QDialog GUIEnabled = True app = QgsApplication([], GUIEnabled) dlg = QDialog() dlg.exec_() app.exit(app.exec_())
class RoamApp(object): def __init__(self, sysargv, apppath, prefixpath, settingspath, libspath, i18npath, projectsroot): self.sysargv = sysargv self.apppath = apppath self.prefixpath = prefixpath self.settingspath = settingspath self.approot = apppath self.profileroot = apppath self.libspath = libspath self.i18npath = i18npath self.app = None self.translationFile = None self.projectsroot = projectsroot self._oldhook = sys.excepthook self.sourcerun = False def init(self, logo, title): from qgis.core import QgsApplication from PyQt4.QtGui import QApplication, QFont, QIcon from PyQt4.QtCore import QLocale, QTranslator try: import PyQt4.QtSql except ImportError: pass self.app = QgsApplication(self.sysargv, True) QgsApplication.setPrefixPath(self.prefixpath, True) QgsApplication.initQgis() locale = QLocale.system().name() self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale)) translator = QTranslator() translator.load(self.translationFile, "i18n") self.app.installTranslator(translator) QApplication.setStyle("Plastique") QApplication.setFont(QFont('Segoe UI')) QApplication.setWindowIcon(QIcon(logo)) QApplication.setApplicationName(title) import roam.editorwidgets.core roam.editorwidgets.core.registerallwidgets() import roam.qgisfunctions return self def set_error_handler(self, errorhandler, logger): sys.excepthook = functools.partial(self.excepthook, errorhandler) self.logger = logger def excepthook(self, errorhandler, exctype, value, traceback): self.logger.error("Uncaught exception", exc_info=(exctype, value, traceback)) errorhandler(exctype, value, traceback) def exec_(self): self.app.exec_() def exit(self): sys.excepthook = self._oldhook from qgis.core import QgsApplication QgsApplication.exitQgis() QgsApplication.quit() def setActiveWindow(self, widget): self.app.setActiveWindow(widget) def dump_configinfo(self): from qgis.core import QgsApplication, QgsProviderRegistry from PyQt4.QtGui import QImageReader, QImageWriter import roam from qgis.core import QGis config = [] config.append("====Providers===") config.append(QgsProviderRegistry.instance().pluginList()) config.append("====Library paths===") config.append('\n'.join(QgsApplication.libraryPaths())) config.append("====Translation File===") config.append(self.translationFile) config.append("Roam Version: {}".format(roam.__version__)) config.append(u"QGIS Version: {}".format(unicode(QGis.QGIS_VERSION))) return '\n'.join(config)
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)
self.layer_tree_view.setCurrentLayer(layer) # 设置需要识别的图层 self.identifyTool.setLayer(layer) elif data_file.endswith('.qgz') or data_file.endswith('.qgs'): QgsProject.instance().read(data_file) else: print('error') def print_features(self, feature): print(feature.attributes()) print(feature.fields()) print(feature.geometry()) if __name__ == '__main__': # 应用入口,使用GUI qgs = QgsApplication([], True) # 设置,qgis安装路径,这里写相对路径,如果是源码运行,这行可不写 qgs.setPrefixPath('qgis', True) # 初始化 qgs.initQgis() window = Window() window.show() exit_code = qgs.exec_() # 退出 qgs.exitQgis()
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()
root = QgsProject.instance().layerTreeRoot() bridge = QgsLayerTreeMapCanvasBridge(root, canvas) count = 0 def prepareMap(): # Arrange layers for lyr in otherLayers.values(): # make all layers invisible root.findLayer(lyr.id()).setVisible(0) # Unchecked root.findLayer(otherLayers.values()[count].id()).setVisible(2) # Checked canvas.zoomToFullExtent() QTimer.singleShot(1000, exportMap) # Wait a second and export the map def exportMap(): # Save the map as a PNG global count # We need this because we'll modify its value canvas.saveAsImage(pngsPath + otherLayers.keys()[count] + ".png") print "Map with layer", otherLayers.keys()[count], "exported!" if count < len(otherLayers) - 1: QTimer.singleShot(1000, prepareMap) # Wait a second and prepare next map else: # Time to close everything qgisApp.exitQgis() qgisApp.exit() count += 1 prepareMap() # Let's start the fun qgisApp.exec_()