class SystemTrayIcon(QSystemTrayIcon): def __init__(self,icons,parent=None): self.icons = icons QSystemTrayIcon.__init__(self,icons[0],parent) self.menu = QMenu(parent) self.menu.addAction("Update",lambda:forceupdate()) self.menu.addAction("Exit",lambda:close()) self.setContextMenu(self.menu) self.actions = [] def update(self): global data flag = False for a in self.actions: self.menu.removeAction(a) for key in data: a = QAction(key+": " + str(data[key]), self.menu) self.actions.append(a) self.menu.addAction(a) x = data[key] if x > 0: flag = True if flag: self.setIcon(icons[1]) else: self.setIcon(icons[0])
class NgiiDataUtils: """QGIS Plugin Implementation.""" mainMenuTitle = u"NGII" mainMenu = None menuBar = None menuActions = [] toolbarActions = [] def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'NgiiDataUtils_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.pluginIsActive = False self.dockwidget = None def initGui(self): # 메뉴와 툴바에 추가할 항목 정의 menuIcons = ['icon.png'] menuTexts = [u'국토지리정보원 공간정보 중첩 검사'] menuActions = [self.togglePanel] assert (len(menuIcons) == len(menuTexts)) assert (len(menuTexts) == len(menuActions)) # 기존 NGII 메뉴가 있으면 재사용. 없으면 추가 self.addNgiiMenu(menuIcons, menuTexts, menuActions) # self.togglePanel() def addNgiiMenu(self, menuIcons, menuTexts, menuActions): # https://gis.stackexchange.com/questions/227876/finding-name-of-qgis-toolbar-in-python qgisMenuBar = self.iface.mainWindow().menuBar() # 이미 NGII 메뉴 있는지 찾아보기 ngiiMenu = None for action in qgisMenuBar.actions(): if action.text() == self.mainMenuTitle: ngiiMenu = action.menu() break # 없음 만들고 있음 그냥 사용 if ngiiMenu is None: self.mainMenu = QMenu(self.iface.mainWindow()) self.mainMenu.setTitle(self.mainMenuTitle) qgisMenuBar.insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.mainMenu) else: self.mainMenu = ngiiMenu # 이미 NGII 툴바 있는지 찾아보기 ngiiToolbar = None for toolbar in self.iface.mainWindow().findChildren(QToolBar): # if toolbar.objectName() == self.mainMenuTitle: if toolbar.windowTitle() == self.mainMenuTitle: ngiiToolbar = toolbar break # 없음 만들고 있음 그냥 사용 if ngiiToolbar is None: self.toolbar = self.iface.addToolBar(self.mainMenuTitle) self.toolbar.setObjectName(self.mainMenuTitle) else: self.toolbar = ngiiToolbar # 세부 메뉴, 버튼 추가 self.menuActions = [] self.toolbarActions = [] for i in range(0, len(menuTexts)): icon = QIcon( os.path.join(os.path.dirname(__file__), 'icons', menuIcons[i])) text = menuTexts[i] action = QAction(icon, text, self.iface.mainWindow()) self.mainMenu.addAction(action) action.triggered.connect(menuActions[i]) button = self.toolbar.addAction(icon, text, menuActions[i]) self.menuActions.append(action) self.toolbarActions.append(button) def removeNgiiMenu(self): if self.toolbar is not None: # 내가 등록한 툴바 아이템 제거 for action in self.toolbarActions: self.toolbar.removeAction(action) # 더이상 항목이 없으면 부모 제거 if len(self.toolbar.actions()) == 0: self.toolbar.deleteLater() if self.mainMenu is not None: for action in self.menuActions: self.mainMenu.removeAction(action) # print len(self.mainMenu.actions()) if len(self.mainMenu.actions()) == 0: self.mainMenu.deleteLater() #-------------------------------------------------------------------------- def onClosePlugin(self): """Cleanup necessary items here when plugin dockwidget is closed""" # print "** CLOSING NgiiDataUtils" # disconnects self.dockwidget.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dockwidget is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: # self.dockwidget = None self.pluginIsActive = False def unload(self): if self.dockwidget: self.iface.removeDockWidget(self.dockwidget) self.removeNgiiMenu() #-------------------------------------------------------------------------- def togglePanel(self): if not self.pluginIsActive: self.pluginIsActive = True # print "** STARTING NgiiDataUtils" # dockwidget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) if self.dockwidget == None: # Create the dockwidget (after translation) and keep reference self.dockwidget = NgiiDataUtilsDockWidget(self.iface) # connect to provide cleanup on closing of dockwidget self.dockwidget.closingPlugin.connect(self.onClosePlugin) # show the dockwidget self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget) # 좌우로 붙게 수정 self.dockwidget.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.dockwidget.show() else: if self.dockwidget: self.dockwidget.close()
class GdalTools: def __init__(self, iface): if not valid: return # Save reference to the QGIS interface self.iface = iface try: self.QgisVersion = unicode(QGis.QGIS_VERSION_INT) except: self.QgisVersion = unicode(QGis.qgisVersion)[0] if QGis.QGIS_VERSION[0:3] < "1.5": # For i18n support userPluginPath = qgis.utils.home_plugin_path + "/GdalTools" systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools" overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool) if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value("locale/userLocale", "", type=str) if QFileInfo(userPluginPath).exists(): translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" else: translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" self.localePath = translationPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator) # The list of actions added to menus, so we can remove them when unloading the plugin self._menuActions = [] def initGui(self): if not valid: return if int(self.QgisVersion) < 1: QMessageBox.warning( self.iface.getMainWindow(), "Gdal Tools", QCoreApplication.translate("GdalTools", "QGIS version detected: ") + unicode(self.QgisVersion) + ".xx\n" + QCoreApplication.translate("GdalTools", "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled.")) return None from tools.GdalTools_utils import GdalConfig, LayerRegistry self.GdalVersionNum = GdalConfig.versionNum() LayerRegistry.setIface(self.iface) # find the Raster menu rasterMenu = None menu_bar = self.iface.mainWindow().menuBar() actions = menu_bar.actions() rasterText = QCoreApplication.translate("QgisApp", "&Raster") for a in actions: if a.menu() is not None and a.menu().title() == rasterText: rasterMenu = a.menu() break if rasterMenu is None: # no Raster menu, create and insert it before the Help menu self.menu = QMenu(rasterText, self.iface.mainWindow()) lastAction = actions[len(actions) - 1] menu_bar.insertMenu(lastAction, self.menu) else: self.menu = rasterMenu self._menuActions.append(self.menu.addSeparator()) # projections menu (Warp (Reproject), Assign projection) self.projectionsMenu = QMenu(QCoreApplication.translate("GdalTools", "Projections"), self.iface.mainWindow()) self.projectionsMenu.setObjectName("projectionsMenu") self.warp = QAction(QIcon(":/icons/warp.png"), QCoreApplication.translate("GdalTools", "Warp (Reproject)..."), self.iface.mainWindow()) self.warp.setObjectName("warp") self.warp.setStatusTip(QCoreApplication.translate("GdalTools", "Warp an image into a new coordinate system")) QObject.connect(self.warp, SIGNAL("triggered()"), self.doWarp) self.projection = QAction(QIcon(":icons/projection-add.png"), QCoreApplication.translate("GdalTools", "Assign Projection..."), self.iface.mainWindow()) self.projection.setObjectName("projection") self.projection.setStatusTip(QCoreApplication.translate("GdalTools", "Add projection info to the raster")) QObject.connect(self.projection, SIGNAL("triggered()"), self.doProjection) self.extractProj = QAction(QIcon(":icons/projection-export.png"), QCoreApplication.translate("GdalTools", "Extract Projection..."), self.iface.mainWindow()) self.extractProj.setObjectName("extractProj") self.extractProj.setStatusTip(QCoreApplication.translate("GdalTools", "Extract projection information from raster(s)")) QObject.connect(self.extractProj, SIGNAL("triggered()"), self.doExtractProj) self.projectionsMenu.addActions([self.warp, self.projection, self.extractProj]) # conversion menu (Rasterize (Vector to raster), Polygonize (Raster to vector), Translate, RGB to PCT, PCT to RGB) self.conversionMenu = QMenu(QCoreApplication.translate("GdalTools", "Conversion"), self.iface.mainWindow()) self.conversionMenu.setObjectName("conversionMenu") if self.GdalVersionNum >= 1300: self.rasterize = QAction(QIcon(":/icons/rasterize.png"), QCoreApplication.translate("GdalTools", "Rasterize (Vector to Raster)..."), self.iface.mainWindow()) self.rasterize.setObjectName("rasterize") self.rasterize.setStatusTip(QCoreApplication.translate("GdalTools", "Burns vector geometries into a raster")) QObject.connect(self.rasterize, SIGNAL("triggered()"), self.doRasterize) self.conversionMenu.addAction(self.rasterize) if self.GdalVersionNum >= 1600: self.polygonize = QAction(QIcon(":/icons/polygonize.png"), QCoreApplication.translate("GdalTools", "Polygonize (Raster to Vector)..."), self.iface.mainWindow()) self.polygonize.setObjectName("polygonize") self.polygonize.setStatusTip(QCoreApplication.translate("GdalTools", "Produces a polygon feature layer from a raster")) QObject.connect(self.polygonize, SIGNAL("triggered()"), self.doPolygonize) self.conversionMenu.addAction(self.polygonize) self.translate = QAction(QIcon(":/icons/translate.png"), QCoreApplication.translate("GdalTools", "Translate (Convert Format)..."), self.iface.mainWindow()) self.translate.setObjectName("translate") self.translate.setStatusTip(QCoreApplication.translate("GdalTools", "Converts raster data between different formats")) QObject.connect(self.translate, SIGNAL("triggered()"), self.doTranslate) self.paletted = QAction(QIcon(":icons/24-to-8-bits.png"), QCoreApplication.translate("GdalTools", "RGB to PCT..."), self.iface.mainWindow()) self.paletted.setObjectName("paletted") self.paletted.setStatusTip(QCoreApplication.translate("GdalTools", "Convert a 24bit RGB image to 8bit paletted")) QObject.connect(self.paletted, SIGNAL("triggered()"), self.doPaletted) self.rgb = QAction(QIcon(":icons/8-to-24-bits.png"), QCoreApplication.translate("GdalTools", "PCT to RGB..."), self.iface.mainWindow()) self.rgb.setObjectName("rgb") self.rgb.setStatusTip(QCoreApplication.translate("GdalTools", "Convert an 8bit paletted image to 24bit RGB")) QObject.connect(self.rgb, SIGNAL("triggered()"), self.doRGB) self.conversionMenu.addActions([self.translate, self.paletted, self.rgb]) # extraction menu (Clipper, Contour) self.extractionMenu = QMenu(QCoreApplication.translate("GdalTools", "Extraction"), self.iface.mainWindow()) self.extractionMenu.setObjectName("extractionMenu") if self.GdalVersionNum >= 1600: self.contour = QAction(QIcon(":/icons/contour.png"), QCoreApplication.translate("GdalTools", "Contour..."), self.iface.mainWindow()) self.contour.setObjectName("contour") self.contour.setStatusTip(QCoreApplication.translate("GdalTools", "Builds vector contour lines from a DEM")) QObject.connect(self.contour, SIGNAL("triggered()"), self.doContour) self.extractionMenu.addAction(self.contour) self.clipper = QAction(QIcon(":icons/raster-clip.png"), QCoreApplication.translate("GdalTools", "Clipper..."), self.iface.mainWindow()) self.clipper.setObjectName("clipper") #self.clipper.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats") ) QObject.connect(self.clipper, SIGNAL("triggered()"), self.doClipper) self.extractionMenu.addActions([self.clipper]) # analysis menu (DEM (Terrain model), Grid (Interpolation), Near black, Proximity (Raster distance), Sieve) self.analysisMenu = QMenu(QCoreApplication.translate("GdalTools", "Analysis"), self.iface.mainWindow()) self.analysisMenu.setObjectName("analysisMenu") if self.GdalVersionNum >= 1600: self.sieve = QAction(QIcon(":/icons/sieve.png"), QCoreApplication.translate("GdalTools", "Sieve..."), self.iface.mainWindow()) self.sieve.setObjectName("sieve") self.sieve.setStatusTip(QCoreApplication.translate("GdalTools", "Removes small raster polygons")) QObject.connect(self.sieve, SIGNAL("triggered()"), self.doSieve) self.analysisMenu.addAction(self.sieve) if self.GdalVersionNum >= 1500: self.nearBlack = QAction(QIcon(":/icons/nearblack.png"), QCoreApplication.translate("GdalTools", "Near Black..."), self.iface.mainWindow()) self.nearBlack.setObjectName("nearBlack") self.nearBlack.setStatusTip(QCoreApplication.translate("GdalTools", "Convert nearly black/white borders to exact value")) QObject.connect(self.nearBlack, SIGNAL("triggered()"), self.doNearBlack) self.analysisMenu.addAction(self.nearBlack) if self.GdalVersionNum >= 1700: self.fillNodata = QAction(QIcon(":/icons/fillnodata.png"), QCoreApplication.translate("GdalTools", "Fill nodata..."), self.iface.mainWindow()) self.fillNodata.setObjectName("fillNodata") self.fillNodata.setStatusTip(QCoreApplication.translate("GdalTools", "Fill raster regions by interpolation from edges")) QObject.connect(self.fillNodata, SIGNAL("triggered()"), self.doFillNodata) self.analysisMenu.addAction(self.fillNodata) if self.GdalVersionNum >= 1600: self.proximity = QAction(QIcon(":/icons/proximity.png"), QCoreApplication.translate("GdalTools", "Proximity (Raster Distance)..."), self.iface.mainWindow()) self.proximity.setObjectName("proximity") self.proximity.setStatusTip(QCoreApplication.translate("GdalTools", "Produces a raster proximity map")) QObject.connect(self.proximity, SIGNAL("triggered()"), self.doProximity) self.analysisMenu.addAction(self.proximity) if self.GdalVersionNum >= 1500: self.grid = QAction(QIcon(":/icons/grid.png"), QCoreApplication.translate("GdalTools", "Grid (Interpolation)..."), self.iface.mainWindow()) self.grid.setObjectName("grid") self.grid.setStatusTip(QCoreApplication.translate("GdalTools", "Create raster from the scattered data")) QObject.connect(self.grid, SIGNAL("triggered()"), self.doGrid) self.analysisMenu.addAction(self.grid) if self.GdalVersionNum >= 1700: self.dem = QAction(QIcon(":icons/dem.png"), QCoreApplication.translate("GdalTools", "DEM (Terrain Models)..."), self.iface.mainWindow()) self.dem.setObjectName("dem") self.dem.setStatusTip(QCoreApplication.translate("GdalTools", "Tool to analyze and visualize DEMs")) QObject.connect(self.dem, SIGNAL("triggered()"), self.doDEM) self.analysisMenu.addAction(self.dem) #self.analysisMenu.addActions( [ ] ) # miscellaneous menu (Build overviews (Pyramids), Tile index, Information, Merge, Build Virtual Raster (Catalog)) self.miscellaneousMenu = QMenu(QCoreApplication.translate("GdalTools", "Miscellaneous"), self.iface.mainWindow()) self.miscellaneousMenu.setObjectName("miscellaneousMenu") if self.GdalVersionNum >= 1600: self.buildVRT = QAction(QIcon(":/icons/vrt.png"), QCoreApplication.translate("GdalTools", "Build Virtual Raster (Catalog)..."), self.iface.mainWindow()) self.buildVRT.setObjectName("buildVRT") self.buildVRT.setStatusTip(QCoreApplication.translate("GdalTools", "Builds a VRT from a list of datasets")) QObject.connect(self.buildVRT, SIGNAL("triggered()"), self.doBuildVRT) self.miscellaneousMenu.addAction(self.buildVRT) self.merge = QAction(QIcon(":/icons/merge.png"), QCoreApplication.translate("GdalTools", "Merge..."), self.iface.mainWindow()) self.merge.setObjectName("merge") self.merge.setStatusTip(QCoreApplication.translate("GdalTools", "Build a quick mosaic from a set of images")) QObject.connect(self.merge, SIGNAL("triggered()"), self.doMerge) self.info = QAction(QIcon(":/icons/raster-info.png"), QCoreApplication.translate("GdalTools", "Information..."), self.iface.mainWindow()) self.info.setObjectName("info") self.info.setStatusTip(QCoreApplication.translate("GdalTools", "Lists information about raster dataset")) QObject.connect(self.info, SIGNAL("triggered()"), self.doInfo) self.overview = QAction(QIcon(":icons/raster-overview.png"), QCoreApplication.translate("GdalTools", "Build Overviews (Pyramids)..."), self.iface.mainWindow()) self.overview.setObjectName("overview") self.overview.setStatusTip(QCoreApplication.translate("GdalTools", "Builds or rebuilds overview images")) QObject.connect(self.overview, SIGNAL("triggered()"), self.doOverview) self.tileindex = QAction(QIcon(":icons/tiles.png"), QCoreApplication.translate("GdalTools", "Tile Index..."), self.iface.mainWindow()) self.tileindex.setObjectName("tileindex") self.tileindex.setStatusTip(QCoreApplication.translate("GdalTools", "Build a shapefile as a raster tileindex")) QObject.connect(self.tileindex, SIGNAL("triggered()"), self.doTileIndex) self.miscellaneousMenu.addActions([self.merge, self.info, self.overview, self.tileindex]) self._menuActions.append(self.menu.addMenu(self.projectionsMenu)) self._menuActions.append(self.menu.addMenu(self.conversionMenu)) self._menuActions.append(self.menu.addMenu(self.extractionMenu)) if not self.analysisMenu.isEmpty(): self._menuActions.append(self.menu.addMenu(self.analysisMenu)) self._menuActions.append(self.menu.addMenu(self.miscellaneousMenu)) self.settings = QAction(QCoreApplication.translate("GdalTools", "GdalTools Settings..."), self.iface.mainWindow()) self.settings.setObjectName("settings") self.settings.setStatusTip(QCoreApplication.translate("GdalTools", "Various settings for Gdal Tools")) QObject.connect(self.settings, SIGNAL("triggered()"), self.doSettings) self.menu.addAction(self.settings) self._menuActions.append(self.settings) def unload(self): if not valid: return for a in self._menuActions: self.menu.removeAction(a) def doBuildVRT(self): from tools.doBuildVRT import GdalToolsDialog as BuildVRT d = BuildVRT(self.iface) self.runToolDialog(d) def doContour(self): from tools.doContour import GdalToolsDialog as Contour d = Contour(self.iface) self.runToolDialog(d) def doRasterize(self): from tools.doRasterize import GdalToolsDialog as Rasterize d = Rasterize(self.iface) self.runToolDialog(d) def doPolygonize(self): from tools.doPolygonize import GdalToolsDialog as Polygonize d = Polygonize(self.iface) self.runToolDialog(d) def doMerge(self): from tools.doMerge import GdalToolsDialog as Merge d = Merge(self.iface) self.runToolDialog(d) def doSieve(self): from tools.doSieve import GdalToolsDialog as Sieve d = Sieve(self.iface) self.runToolDialog(d) def doProximity(self): from tools.doProximity import GdalToolsDialog as Proximity d = Proximity(self.iface) self.runToolDialog(d) def doNearBlack(self): from tools.doNearBlack import GdalToolsDialog as NearBlack d = NearBlack(self.iface) self.runToolDialog(d) def doFillNodata(self): from tools.doFillNodata import GdalToolsDialog as FillNodata d = FillNodata(self.iface) self.runToolDialog(d) def doWarp(self): from tools.doWarp import GdalToolsDialog as Warp d = Warp(self.iface) self.runToolDialog(d) def doGrid(self): from tools.doGrid import GdalToolsDialog as Grid d = Grid(self.iface) self.runToolDialog(d) def doTranslate(self): from tools.doTranslate import GdalToolsDialog as Translate d = Translate(self.iface) self.runToolDialog(d) def doInfo(self): from tools.doInfo import GdalToolsDialog as Info d = Info(self.iface) self.runToolDialog(d) def doProjection(self): from tools.doProjection import GdalToolsDialog as Projection d = Projection(self.iface) self.runToolDialog(d) def doOverview(self): from tools.doOverview import GdalToolsDialog as Overview d = Overview(self.iface) self.runToolDialog(d) def doClipper(self): from tools.doClipper import GdalToolsDialog as Clipper d = Clipper(self.iface) self.runToolDialog(d) def doPaletted(self): from tools.doRgbPct import GdalToolsDialog as RgbPct d = RgbPct(self.iface) self.runToolDialog(d) def doRGB(self): from tools.doPctRgb import GdalToolsDialog as PctRgb d = PctRgb(self.iface) self.runToolDialog(d) def doTileIndex(self): from tools.doTileIndex import GdalToolsDialog as TileIndex d = TileIndex(self.iface) self.runToolDialog(d) def doExtractProj(self): from tools.doExtractProj import GdalToolsDialog as ExtractProj d = ExtractProj(self.iface) d.exec_() def doDEM(self): from tools.doDEM import GdalToolsDialog as DEM d = DEM(self.iface) self.runToolDialog(d) def runToolDialog(self, dlg): dlg.show_() dlg.exec_() del dlg def doSettings(self): from tools.doSettings import GdalToolsSettingsDialog as Settings d = Settings(self.iface) d.exec_()
class Dummy: instance = None def __init__(self, iface): from createunbeffl import application as createunbeffl from importdyna import application as importdyna from exportdyna import application as exportdyna from linkflaechen import application as linkflaechen from tools import application as tools self.plugins = [ createunbeffl.CreateUnbefFl(iface), importdyna.ImportFromDyna(iface), exportdyna.ExportToKP(iface), linkflaechen.LinkFl(iface), tools.QKanTools(iface) ] Dummy.instance = self # Plugins self.instances = [] # QGIS self.iface = iface self.plugin_dir = os.path.dirname(__file__) self.actions = [] actions = self.iface.mainWindow().menuBar().actions() self.menu = None for menu in actions: if menu.text() == 'QKan': self.menu = menu.menu() self.menu_action = menu break self.toolbar = self.iface.addToolBar('QKan') self.toolbar.setObjectName('QKan') def initGui(self): # Create and insert QKan menu after the 3rd menu if self.menu is None: self.menu = QMenu('QKan', self.iface.mainWindow().menuBar()) actions = self.iface.mainWindow().menuBar().actions() prepend = actions[3] self.menu_action = self.iface.mainWindow().menuBar().insertMenu(prepend, self.menu) # Calls initGui on all known QKan plugins for plugin in self.plugins: plugin.initGui() self.sort_actions() def sort_actions(self): # Finally sort all actions self.actions.sort(key=lambda x: x.text().lower()) self.menu.clear() self.menu.addActions(self.actions) def unload(self): from qgis.utils import unloadPlugin # Unload all other instances for instance in self.instances: print('Unloading ', instance.name) if not unloadPlugin(instance.name): print('Failed to unload plugin!') # Remove entries from own menu for action in self.menu.actions(): self.menu.removeAction(action) # Remove entries from Plugin menu and toolbar for action in self.actions: self.iface.removeToolBarIcon(action) # Remove the toolbar del self.toolbar # Remove menu self.iface.mainWindow().menuBar().removeAction(self.menu_action) # Call unload on all loaded plugins for plugin in self.plugins: plugin.unload() def register(self, instance): self.instances.append(instance) self.plugins += instance.plugins def unregister(self, instance): self.instances.remove(instance) for plugin in instance.plugins: self.plugins.remove(plugin) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.__actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.menu.addAction(action) self.actions.append(action) return action
class GdalTools: def __init__(self, iface): if not valid: return # Save reference to the QGIS interface self.iface = iface try: self.QgisVersion = unicode(QGis.QGIS_VERSION_INT) except: self.QgisVersion = unicode(QGis.qgisVersion)[0] if QGis.QGIS_VERSION[0:3] < "1.5": # For i18n support userPluginPath = qgis.utils.home_plugin_path + "/GdalTools" systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools" overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool) if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value("locale/userLocale", "", type=str) if QFileInfo(userPluginPath).exists(): translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" else: translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" self.localePath = translationPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator) # The list of actions added to menus, so we can remove them when unloading the plugin self._menuActions = [] def initGui(self): if not valid: return if int(self.QgisVersion) < 1: QMessageBox.warning( self.iface.getMainWindow(), "Gdal Tools", QCoreApplication.translate("GdalTools", "QGIS version detected: ") + unicode(self.QgisVersion) + ".xx\n" + QCoreApplication.translate( "GdalTools", "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled." )) return None from tools.GdalTools_utils import GdalConfig, LayerRegistry self.GdalVersionNum = GdalConfig.versionNum() LayerRegistry.setIface(self.iface) # find the Raster menu rasterMenu = None menu_bar = self.iface.mainWindow().menuBar() actions = menu_bar.actions() rasterText = QCoreApplication.translate("QgisApp", "&Raster") for a in actions: if a.menu() is not None and a.menu().title() == rasterText: rasterMenu = a.menu() break if rasterMenu is None: # no Raster menu, create and insert it before the Help menu self.menu = QMenu(rasterText, self.iface.mainWindow()) lastAction = actions[len(actions) - 1] menu_bar.insertMenu(lastAction, self.menu) else: self.menu = rasterMenu self._menuActions.append(self.menu.addSeparator()) # projections menu (Warp (Reproject), Assign projection) self.projectionsMenu = QMenu( QCoreApplication.translate("GdalTools", "Projections"), self.iface.mainWindow()) self.projectionsMenu.setObjectName("projectionsMenu") self.warp = QAction( QIcon(":/icons/warp.png"), QCoreApplication.translate("GdalTools", "Warp (Reproject)..."), self.iface.mainWindow()) self.warp.setObjectName("warp") self.warp.setStatusTip( QCoreApplication.translate( "GdalTools", "Warp an image into a new coordinate system")) QObject.connect(self.warp, SIGNAL("triggered()"), self.doWarp) self.projection = QAction( QIcon(":icons/projection-add.png"), QCoreApplication.translate("GdalTools", "Assign Projection..."), self.iface.mainWindow()) self.projection.setObjectName("projection") self.projection.setStatusTip( QCoreApplication.translate("GdalTools", "Add projection info to the raster")) QObject.connect(self.projection, SIGNAL("triggered()"), self.doProjection) self.extractProj = QAction( QIcon(":icons/projection-export.png"), QCoreApplication.translate("GdalTools", "Extract Projection..."), self.iface.mainWindow()) self.extractProj.setObjectName("extractProj") self.extractProj.setStatusTip( QCoreApplication.translate( "GdalTools", "Extract projection information from raster(s)")) QObject.connect(self.extractProj, SIGNAL("triggered()"), self.doExtractProj) self.projectionsMenu.addActions( [self.warp, self.projection, self.extractProj]) # conversion menu (Rasterize (Vector to raster), Polygonize (Raster to vector), Translate, RGB to PCT, PCT to RGB) self.conversionMenu = QMenu( QCoreApplication.translate("GdalTools", "Conversion"), self.iface.mainWindow()) self.conversionMenu.setObjectName("conversionMenu") if self.GdalVersionNum >= 1300: self.rasterize = QAction( QIcon(":/icons/rasterize.png"), QCoreApplication.translate("GdalTools", "Rasterize (Vector to Raster)..."), self.iface.mainWindow()) self.rasterize.setObjectName("rasterize") self.rasterize.setStatusTip( QCoreApplication.translate( "GdalTools", "Burns vector geometries into a raster")) QObject.connect(self.rasterize, SIGNAL("triggered()"), self.doRasterize) self.conversionMenu.addAction(self.rasterize) if self.GdalVersionNum >= 1600: self.polygonize = QAction( QIcon(":/icons/polygonize.png"), QCoreApplication.translate("GdalTools", "Polygonize (Raster to Vector)..."), self.iface.mainWindow()) self.polygonize.setObjectName("polygonize") self.polygonize.setStatusTip( QCoreApplication.translate( "GdalTools", "Produces a polygon feature layer from a raster")) QObject.connect(self.polygonize, SIGNAL("triggered()"), self.doPolygonize) self.conversionMenu.addAction(self.polygonize) self.translate = QAction( QIcon(":/icons/translate.png"), QCoreApplication.translate("GdalTools", "Translate (Convert Format)..."), self.iface.mainWindow()) self.translate.setObjectName("translate") self.translate.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats")) QObject.connect(self.translate, SIGNAL("triggered()"), self.doTranslate) self.paletted = QAction( QIcon(":icons/24-to-8-bits.png"), QCoreApplication.translate("GdalTools", "RGB to PCT..."), self.iface.mainWindow()) self.paletted.setObjectName("paletted") self.paletted.setStatusTip( QCoreApplication.translate( "GdalTools", "Convert a 24bit RGB image to 8bit paletted")) QObject.connect(self.paletted, SIGNAL("triggered()"), self.doPaletted) self.rgb = QAction( QIcon(":icons/8-to-24-bits.png"), QCoreApplication.translate("GdalTools", "PCT to RGB..."), self.iface.mainWindow()) self.rgb.setObjectName("rgb") self.rgb.setStatusTip( QCoreApplication.translate( "GdalTools", "Convert an 8bit paletted image to 24bit RGB")) QObject.connect(self.rgb, SIGNAL("triggered()"), self.doRGB) self.conversionMenu.addActions( [self.translate, self.paletted, self.rgb]) # extraction menu (Clipper, Contour) self.extractionMenu = QMenu( QCoreApplication.translate("GdalTools", "Extraction"), self.iface.mainWindow()) self.extractionMenu.setObjectName("extractionMenu") if self.GdalVersionNum >= 1600: self.contour = QAction( QIcon(":/icons/contour.png"), QCoreApplication.translate("GdalTools", "Contour..."), self.iface.mainWindow()) self.contour.setObjectName("contour") self.contour.setStatusTip( QCoreApplication.translate( "GdalTools", "Builds vector contour lines from a DEM")) QObject.connect(self.contour, SIGNAL("triggered()"), self.doContour) self.extractionMenu.addAction(self.contour) self.clipper = QAction( QIcon(":icons/raster-clip.png"), QCoreApplication.translate("GdalTools", "Clipper..."), self.iface.mainWindow()) self.clipper.setObjectName("clipper") #self.clipper.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats") ) QObject.connect(self.clipper, SIGNAL("triggered()"), self.doClipper) self.extractionMenu.addActions([self.clipper]) # analysis menu (DEM (Terrain model), Grid (Interpolation), Near black, Proximity (Raster distance), Sieve) self.analysisMenu = QMenu( QCoreApplication.translate("GdalTools", "Analysis"), self.iface.mainWindow()) self.analysisMenu.setObjectName("analysisMenu") if self.GdalVersionNum >= 1600: self.sieve = QAction( QIcon(":/icons/sieve.png"), QCoreApplication.translate("GdalTools", "Sieve..."), self.iface.mainWindow()) self.sieve.setObjectName("sieve") self.sieve.setStatusTip( QCoreApplication.translate("GdalTools", "Removes small raster polygons")) QObject.connect(self.sieve, SIGNAL("triggered()"), self.doSieve) self.analysisMenu.addAction(self.sieve) if self.GdalVersionNum >= 1500: self.nearBlack = QAction( QIcon(":/icons/nearblack.png"), QCoreApplication.translate("GdalTools", "Near Black..."), self.iface.mainWindow()) self.nearBlack.setObjectName("nearBlack") self.nearBlack.setStatusTip( QCoreApplication.translate( "GdalTools", "Convert nearly black/white borders to exact value")) QObject.connect(self.nearBlack, SIGNAL("triggered()"), self.doNearBlack) self.analysisMenu.addAction(self.nearBlack) if self.GdalVersionNum >= 1700: self.fillNodata = QAction( QIcon(":/icons/fillnodata.png"), QCoreApplication.translate("GdalTools", "Fill nodata..."), self.iface.mainWindow()) self.fillNodata.setObjectName("fillNodata") self.fillNodata.setStatusTip( QCoreApplication.translate( "GdalTools", "Fill raster regions by interpolation from edges")) QObject.connect(self.fillNodata, SIGNAL("triggered()"), self.doFillNodata) self.analysisMenu.addAction(self.fillNodata) if self.GdalVersionNum >= 1600: self.proximity = QAction( QIcon(":/icons/proximity.png"), QCoreApplication.translate("GdalTools", "Proximity (Raster Distance)..."), self.iface.mainWindow()) self.proximity.setObjectName("proximity") self.proximity.setStatusTip( QCoreApplication.translate("GdalTools", "Produces a raster proximity map")) QObject.connect(self.proximity, SIGNAL("triggered()"), self.doProximity) self.analysisMenu.addAction(self.proximity) if self.GdalVersionNum >= 1500: self.grid = QAction( QIcon(":/icons/grid.png"), QCoreApplication.translate("GdalTools", "Grid (Interpolation)..."), self.iface.mainWindow()) self.grid.setObjectName("grid") self.grid.setStatusTip( QCoreApplication.translate( "GdalTools", "Create raster from the scattered data")) QObject.connect(self.grid, SIGNAL("triggered()"), self.doGrid) self.analysisMenu.addAction(self.grid) if self.GdalVersionNum >= 1700: self.dem = QAction( QIcon(":icons/dem.png"), QCoreApplication.translate("GdalTools", "DEM (Terrain Models)..."), self.iface.mainWindow()) self.dem.setObjectName("dem") self.dem.setStatusTip( QCoreApplication.translate( "GdalTools", "Tool to analyze and visualize DEMs")) QObject.connect(self.dem, SIGNAL("triggered()"), self.doDEM) self.analysisMenu.addAction(self.dem) #self.analysisMenu.addActions( [ ] ) # miscellaneous menu (Build overviews (Pyramids), Tile index, Information, Merge, Build Virtual Raster (Catalog)) self.miscellaneousMenu = QMenu( QCoreApplication.translate("GdalTools", "Miscellaneous"), self.iface.mainWindow()) self.miscellaneousMenu.setObjectName("miscellaneousMenu") if self.GdalVersionNum >= 1600: self.buildVRT = QAction( QIcon(":/icons/vrt.png"), QCoreApplication.translate( "GdalTools", "Build Virtual Raster (Catalog)..."), self.iface.mainWindow()) self.buildVRT.setObjectName("buildVRT") self.buildVRT.setStatusTip( QCoreApplication.translate( "GdalTools", "Builds a VRT from a list of datasets")) QObject.connect(self.buildVRT, SIGNAL("triggered()"), self.doBuildVRT) self.miscellaneousMenu.addAction(self.buildVRT) self.merge = QAction( QIcon(":/icons/merge.png"), QCoreApplication.translate("GdalTools", "Merge..."), self.iface.mainWindow()) self.merge.setObjectName("merge") self.merge.setStatusTip( QCoreApplication.translate( "GdalTools", "Build a quick mosaic from a set of images")) QObject.connect(self.merge, SIGNAL("triggered()"), self.doMerge) self.info = QAction( QIcon(":/icons/raster-info.png"), QCoreApplication.translate("GdalTools", "Information..."), self.iface.mainWindow()) self.info.setObjectName("info") self.info.setStatusTip( QCoreApplication.translate( "GdalTools", "Lists information about raster dataset")) QObject.connect(self.info, SIGNAL("triggered()"), self.doInfo) self.overview = QAction( QIcon(":icons/raster-overview.png"), QCoreApplication.translate("GdalTools", "Build Overviews (Pyramids)..."), self.iface.mainWindow()) self.overview.setObjectName("overview") self.overview.setStatusTip( QCoreApplication.translate("GdalTools", "Builds or rebuilds overview images")) QObject.connect(self.overview, SIGNAL("triggered()"), self.doOverview) self.tileindex = QAction( QIcon(":icons/tiles.png"), QCoreApplication.translate("GdalTools", "Tile Index..."), self.iface.mainWindow()) self.tileindex.setObjectName("tileindex") self.tileindex.setStatusTip( QCoreApplication.translate( "GdalTools", "Build a shapefile as a raster tileindex")) QObject.connect(self.tileindex, SIGNAL("triggered()"), self.doTileIndex) self.miscellaneousMenu.addActions( [self.merge, self.info, self.overview, self.tileindex]) self._menuActions.append(self.menu.addMenu(self.projectionsMenu)) self._menuActions.append(self.menu.addMenu(self.conversionMenu)) self._menuActions.append(self.menu.addMenu(self.extractionMenu)) if not self.analysisMenu.isEmpty(): self._menuActions.append(self.menu.addMenu(self.analysisMenu)) self._menuActions.append(self.menu.addMenu(self.miscellaneousMenu)) self.settings = QAction( QCoreApplication.translate("GdalTools", "GdalTools Settings..."), self.iface.mainWindow()) self.settings.setObjectName("settings") self.settings.setStatusTip( QCoreApplication.translate("GdalTools", "Various settings for Gdal Tools")) QObject.connect(self.settings, SIGNAL("triggered()"), self.doSettings) self.menu.addAction(self.settings) self._menuActions.append(self.settings) def unload(self): if not valid: return for a in self._menuActions: self.menu.removeAction(a) def doBuildVRT(self): from tools.doBuildVRT import GdalToolsDialog as BuildVRT d = BuildVRT(self.iface) self.runToolDialog(d) def doContour(self): from tools.doContour import GdalToolsDialog as Contour d = Contour(self.iface) self.runToolDialog(d) def doRasterize(self): from tools.doRasterize import GdalToolsDialog as Rasterize d = Rasterize(self.iface) self.runToolDialog(d) def doPolygonize(self): from tools.doPolygonize import GdalToolsDialog as Polygonize d = Polygonize(self.iface) self.runToolDialog(d) def doMerge(self): from tools.doMerge import GdalToolsDialog as Merge d = Merge(self.iface) self.runToolDialog(d) def doSieve(self): from tools.doSieve import GdalToolsDialog as Sieve d = Sieve(self.iface) self.runToolDialog(d) def doProximity(self): from tools.doProximity import GdalToolsDialog as Proximity d = Proximity(self.iface) self.runToolDialog(d) def doNearBlack(self): from tools.doNearBlack import GdalToolsDialog as NearBlack d = NearBlack(self.iface) self.runToolDialog(d) def doFillNodata(self): from tools.doFillNodata import GdalToolsDialog as FillNodata d = FillNodata(self.iface) self.runToolDialog(d) def doWarp(self): from tools.doWarp import GdalToolsDialog as Warp d = Warp(self.iface) self.runToolDialog(d) def doGrid(self): from tools.doGrid import GdalToolsDialog as Grid d = Grid(self.iface) self.runToolDialog(d) def doTranslate(self): from tools.doTranslate import GdalToolsDialog as Translate d = Translate(self.iface) self.runToolDialog(d) def doInfo(self): from tools.doInfo import GdalToolsDialog as Info d = Info(self.iface) self.runToolDialog(d) def doProjection(self): from tools.doProjection import GdalToolsDialog as Projection d = Projection(self.iface) self.runToolDialog(d) def doOverview(self): from tools.doOverview import GdalToolsDialog as Overview d = Overview(self.iface) self.runToolDialog(d) def doClipper(self): from tools.doClipper import GdalToolsDialog as Clipper d = Clipper(self.iface) self.runToolDialog(d) def doPaletted(self): from tools.doRgbPct import GdalToolsDialog as RgbPct d = RgbPct(self.iface) self.runToolDialog(d) def doRGB(self): from tools.doPctRgb import GdalToolsDialog as PctRgb d = PctRgb(self.iface) self.runToolDialog(d) def doTileIndex(self): from tools.doTileIndex import GdalToolsDialog as TileIndex d = TileIndex(self.iface) self.runToolDialog(d) def doExtractProj(self): from tools.doExtractProj import GdalToolsDialog as ExtractProj d = ExtractProj(self.iface) d.exec_() def doDEM(self): from tools.doDEM import GdalToolsDialog as DEM d = DEM(self.iface) self.runToolDialog(d) def runToolDialog(self, dlg): dlg.show_() dlg.exec_() del dlg def doSettings(self): from tools.doSettings import GdalToolsSettingsDialog as Settings d = Settings(self.iface) d.exec_()
class trayIcon(QSystemTrayIcon): #================================================================================================================== # CONSTRUCTOR DE LA CLASE #================================================================================================================== def __init__(self, server, icon, parent=None): #-------------------------------------------------------------------------------------------------------------- # INICIAR Y CONFIGURAR LA INSTANCIA #-------------------------------------------------------------------------------------------------------------- QSystemTrayIcon.__init__(self, icon, parent) # Iniciar la instancia self.parent = parent # Almacenar referencia hacia el padre self.server = server #-------------------------------------------------------------------------------------------------------------- # MENU #-------------------------------------------------------------------------------------------------------------- self.menu = QMenu(self.parent) # Definir menú para el trayIcon self.setContextMenu(self.menu) # Enlazar menú con el trayIcon self.showWindow = QAction("Mostrar", self) # Crear acción para mostrar la aplicación self.showWindow.triggered.connect(self.parent.show) # Conectarla con mostrar la ventana de login self.menu.addAction(self.showWindow) # Añadir la acción al menú self.logout = QAction("Cerrar sesión", self) # Crear acción para logout self.logout.triggered.connect(self.parent.closeSession_pressed) # Conectarla con mostrar la ventana de login self.kill = QAction("Salir", self) # Crear acción para cerrar la aplicación self.kill.triggered.connect(self.killApp) # Conectarla con cerrar el programa self.menu.addAction(self.kill) # Añadir la acción al menú #-------------------------------------------------------------------------------------------------------------- # SEÑALES #-------------------------------------------------------------------------------------------------------------- # Conectar la señal de cerrar la ventana principal y cerrar la sesióm self.parent.sessionClosed.connect(self.sessionClosed) # Conectar la señal de cerrar la ventana principal y NO cerrar la sesióm self.parent.sessionAlive.connect(self.sessionAlive) #================================================================================================================== # MÉTODOS #================================================================================================================== # Método para atrapar la señal de cerrar la ventana principal y cerrar la sesióm def sessionClosed(self): self.showWindow.triggered.disconnect() # Desconectar la acción self.showWindow.triggered.connect(self.parent.show) # Y reconectar con mostrar la ventana de login self.menu.removeAction(self.logout) # Añadir la acción al menú # Método para atrapar la señal de cerrar la ventana principal y NO cerrar la sesióm def sessionAlive(self): self.showWindow.triggered.disconnect() # Desconectar la acción self.showWindow.triggered.connect(self.parent.mainWindow.show) # Y reconectar con mostrar la ventana principal self.menu.insertAction(self.kill, self.logout) # Añadir la acción al menú # Método para terminar el programa def killApp(self): if self.parent.guiExist: # Si existe la ventana principal mainWindow = self.parent.mainWindow # Apuntador hacia la ventana principal if mainWindow.db.isOpenTurn(): # Si hay un turno abierto mainWindow.db.closeTurn(mainWindow.user) # Cerrar turno del usuario de la ventana principal mainWindow.close() # Cerrar la ventana principal self.parent.db.close() # Cerrar la sesión en la base de datos self.parent.close() # Cerrar la ventana de login self.server.close() # Cerrar el servidor de la aplicación exit(0) # Salir del programa
class MainWindow(QWidget): def __init__(self): super(QWidget, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.systemTray = QSystemTrayIcon(self) self.systemTray.setIcon(QIcon(':/images/icon.png')) self.act_autostart = QAction('开机启动', self) self.act_autostart.setCheckable(True) is_autostart = self.is_autostart() self.act_autostart.setChecked(is_autostart) self.act_autostart.triggered.connect(self.on_autostart) act_setting = QAction('设置启动项', self) act_setting.triggered.connect(self.on_settings) act_exit = QAction('退出', self) act_exit.triggered.connect(self.on_exit) self.menu_run = QMenu('运行', self) menu = QMenu('菜单', self) menu.addMenu(self.menu_run) menu.addAction(act_setting) menu.addSeparator() menu.addAction(self.act_autostart) menu.addAction(act_exit) self.systemTray.setContextMenu(menu) self.systemTray.show() self.showMessage('启动工具正在运行') self.ui.btn_add.clicked.connect(self.on_add) self.ui.btn_delete.clicked.connect(self.on_delete) self.ui.btn_apply.clicked.connect(self.on_apply) self.ui.btn_env_add.clicked.connect(self.on_env_add) self.ui.btn_env_del.clicked.connect(self.on_env_del) self.ui.btn_open.clicked.connect(self.on_open) self.ui.btn_run.clicked.connect(self.on_run) self.ui.le_args.textEdited.connect(self.on_edited) self.ui.le_desc.textEdited.connect(self.on_edited) self.ui.le_exe.textEdited.connect(self.on_edited) self.ui.cb_process.currentIndexChanged.connect(self.on_index_changed) self.ui.le_exe.installEventFilter(self) self.init() def eventFilter(self, obj, event): if event.type() == QEvent.DragEnter: # we need to accept this event explicitly to be able to receive QDropEvents! event.accept() if event.type() == QEvent.Drop: md = event.mimeData() urls = md.urls() if (urls and urls[0].scheme() == 'file'): # for some reason, this doubles up the intro slash filepath = urls[0].path().mid(1) self.ui.le_exe.setText(filepath) self.modify = True self.ui.btn_apply.setEnabled(True) event.accept() return QObject.eventFilter(self, obj, event) def showMessage(self, msg): self.systemTray.showMessage('Launcher', msg, QSystemTrayIcon.Information, 10000) def config_dir(self): confd = QString2str( QApplication.applicationDirPath()) + os.sep + 'configs' dir = QDir(confd) if not dir.exists(): dir.mkpath(confd) return confd def on_settings(self): self.show() def on_exit(self): QtGui.qApp.quit() def on_edited(self): self.modify = True self.ui.btn_apply.setEnabled(True) def on_apply(self): if self.currentProcess is None: QMessageBox.warning(self, '警告', '未选择有效启动项,无法完成保存!') return args = self.ui.le_args.text() exe = self.ui.le_exe.text() desc = self.ui.le_desc.text() isInherit = self.ui.cb_inheri.checkState() == QtCore.Qt.Checked self.currentProcess.setArgs(QString2str(args)) self.currentProcess.setExe(QString2str(exe)) self.currentProcess.setDesc(QString2str(desc)) self.currentProcess.setIsInherit(isInherit) envs = {} for i in range(self.ui.tw_envs.rowCount()): key = self.ui.tw_envs.item(i, 0).text() value = self.ui.tw_envs.item(i, 1).text() envs[QString2str(key)] = QString2str(value) self.currentProcess.setEnvs(envs) self.processDict[self.currentProcess.getName()] = self.currentProcess configDir = self.config_dir() configFilePath = configDir + os.sep + self.currentProcess.getName( ) + '.json' with open(configFilePath, 'w+') as f: f.write(self.currentProcess.save()) self.modify = False self.ui.btn_apply.setEnabled(False) QMessageBox.information(self, '提示', '已保存!') def on_add(self): ret = QInputDialog.getText(self, '请输入启动项目名称', '名称') if not ret[1]: return name = ret[0] if name.isEmpty(): return if self.processDict.has_key(QString2str(name)): QMessageBox.warning(self, '警告', '该启动项已存在!') return curProcess = Process() curProcess.setName(QString2str(name)) configDir = self.config_dir() configFilePath = configDir + os.sep + QString2str(name) + '.json' with open(configFilePath, 'w+') as f: f.write(curProcess.save()) self.add_item(curProcess) self.ui.cb_process.setCurrentIndex(self.ui.cb_process.count() - 1) def on_delete(self): name = self.ui.cb_process.currentText() index = self.ui.cb_process.currentIndex() if not self.processDict.has_key(QString2str(name)): QMessageBox.warning(self, '警告', '请先选择要删除的配置项!') return process = self.processDict.pop(QString2str(name)) for action in self.menu_run.actions(): if action.text() == name: self.menu_run.removeAction(action) self.ui.cb_process.removeItem(index) configFilePath = self.config_dir() + os.sep + QString2str( name) + '.json' os.remove(configFilePath) def on_index_changed(self, index): if self.modify and QMessageBox.question( self, '提示', '启动项已修改,是否保存?', QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes: self.on_apply() name = self.ui.cb_process.itemText(index) self.reset() if self.processDict.has_key(QString2str(name)): process = self.processDict[QString2str(name)] self.currentProcess = process self.display(process) def on_env_add(self): self.ui.tw_envs.setRowCount(self.ui.tw_envs.rowCount() + 1) self.modify = True self.ui.btn_apply.setEnabled(True) def on_env_del(self): index = self.ui.tw_envs.currentRow() self.ui.tw_envs.removeRow(index) self.modify = True self.ui.btn_apply.setEnabled(True) def on_run(self): if self.modify and QMessageBox.question( self, '提示', '启动项已修改,是否保存?', QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes: self.on_apply() name = self.ui.cb_process.currentText() if self.processDict.has_key(QString2str(name)): process = self.processDict[QString2str(name)] if process.start(): self.showMessage(u'%s启动项已执行' % process.getName()) else: self.showMessage(u'%s启动项执行失败,请检查配置' % process.getName()) else: QMessageBox.warning(self, '警告', '请先选择要运行的启动项!') def on_action_run(self): name = self.sender().text() if self.processDict.has_key(QString2str(name)): process = self.processDict[QString2str(name)] if process.start(): self.showMessage(u'%s启动项已执行' % process.getName()) else: self.showMessage(u'%s启动项执行失败,请检查配置' % process.getName()) else: QMessageBox.warning(self, '警告', '请先选择要运行的启动项!') def on_open(self): filePath = QFileDialog.getOpenFileName(self, '选择程序') self.ui.le_exe.setText(filePath) self.modify = True self.ui.btn_apply.setEnabled(True) def closeEvent(self, event): event.ignore() self.hide() def add_item(self, process): self.processDict[process.getName()] = process self.ui.cb_process.addItem(process.getName()) act = self.menu_run.addAction(process.getName()) act.triggered.connect(self.on_action_run) def init(self): self.modify = False self.ui.btn_apply.setEnabled(False) self.currentProcess = None self.processDict = {} config_dir = self.config_dir() items = os.listdir(config_dir) for item in items: currentPath = self.config_dir() + os.sep + item if not os.path.isdir(currentPath) and os.path.exists(currentPath): with open(currentPath, 'r') as f: content = f.read() process = Process() if process.load(content): self.add_item(process) def reset(self): self.ui.le_args.setText('') self.ui.le_exe.setText('') self.ui.le_desc.setText('') self.ui.tw_envs.clear() self.ui.tw_envs.setRowCount(0) self.modify = False self.ui.btn_apply.setEnabled(False) def display(self, process): self.ui.le_args.setText(process.getArgs()) self.ui.le_exe.setText(process.getExe()) self.ui.le_desc.setText(process.getDesc()) envs = process.getEnvs() for key in envs.keys(): row = self.ui.tw_envs.rowCount() self.ui.tw_envs.setRowCount(row + 1) self.ui.tw_envs.setItem(row, 0, QTableWidgetItem(key)) self.ui.tw_envs.setItem(row, 1, QTableWidgetItem(envs[key])) def on_autostart(self): if self.act_autostart.isChecked(): self.set_autostart(True) self.showMessage('已设置开机启动') else: self.set_autostart(False) self.showMessage('已取消开机启动') def is_autostart(self): reg = QSettings( "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings.NativeFormat) return reg.contains("launcher") def set_autostart(self, auto): path = QApplication.applicationFilePath() path = QDir.toNativeSeparators(path) reg = QSettings( "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings.NativeFormat) if auto is True: reg.setValue("launcher", QVariant(QString('"%1"').arg(path))) else: reg.remove("launcher")