Example #1
0
class LocationLab:

    def __init__(self, iface):
        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        self.plugin_dir = os.path.dirname(__file__)
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'LocationLab{}.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.actions = []
        self.menu = QMenu(self.iface.mainWindow())
        self.menu.setObjectName('locationLab')
        self.menu.setTitle(u'&Location Lab')
        # Init modules
        self.catchmentsModule = CatchmentsModule(self)
        self.infoModule = InfoModule(self)
        

    def tr(self, message):
        return QCoreApplication.translate('Catchments', message)

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        checkable=False
            ):

        icon = QIcon(icon_path)
        action = QAction(icon, text, self.iface.mainWindow())
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)
        action.setCheckable(checkable)
        self.menu.addAction(action)
        self.actions.append(action)
        return action

    def initGui(self):
        self.add_action(
            ':/plugins/LocationLab/catchments.png',
            text=self.tr(u'Catchments'),
            callback=self.catchmentsModule.show)
        self.add_action(
           ':/plugins/LocationLab/info.png',
           text=self.tr(u'Info'),
           callback=self.infoModule.show)
        menuBar = self.iface.mainWindow().menuBar()
        menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu)

    def unload(self):
        self.menu.deleteLater()
Example #2
0
    def contextMenuEvent(self, ev):
        index = self.indexAt(ev.pos())
        if not index.isValid():
            return

        if index != self.currentIndex():
            self.itemChanged(index)

        item = self.currentItem()

        menu = QMenu(self)

        if isinstance(item, (Table, Schema)):
            menu.addAction(self.tr("Rename"), self.rename)
            menu.addAction(self.tr("Delete"), self.delete)

            if isinstance(item, Table) and item.canBeAddedToCanvas():
                menu.addSeparator()
                menu.addAction(self.tr("Add to canvas"), self.addLayer)

        elif isinstance(item, DBPlugin):
            if item.database() is not None:
                menu.addAction(self.tr("Re-connect"), self.reconnect)
            menu.addAction(self.tr("Remove"), self.delete)

        elif not index.parent().isValid() and item.typeName() == "spatialite":
            menu.addAction(self.tr("New Connection..."), self.newConnection)

        if not menu.isEmpty():
            menu.exec_(ev.globalPos())

        menu.deleteLater()
 def _showImageContextMenu(self, _point):
     pixmap = self.imageLabel.getRawPixmap()
     if pixmap is None or pixmap.isNull():
         return
     m = QMenu()
     m.addAction(u"Set as category thumbnail", self._setCurrentPictureAsThumbnail)
     m.exec_(QCursor.pos())
     m.deleteLater()
Example #4
0
    def contextMenuEvent(self, ev):
        item = self.itemAt(ev.pos())
        if not item:
            return

        mainwindow = self.parentWidget().mainwindow()

        selection = self.selectedItems()
        doc = self.document(item)

        if len(selection) <= 1 and doc:
            # a single document is right-clicked
            import documentcontextmenu
            menu = documentcontextmenu.DocumentContextMenu(mainwindow)
            menu.exec_(doc, ev.globalPos())
            menu.deleteLater()
            return

        menu = QMenu(mainwindow)
        save = menu.addAction(icons.get('document-save'), '')
        menu.addSeparator()
        close = menu.addAction(icons.get('document-close'), '')

        if len(selection) > 1:
            # multiple documents are selected
            save.setText(_("Save selected documents"))
            close.setText(_("Close selected documents"))
            documents = [self.document(item) for item in selection]
        else:
            documents = [
                self.document(item.child(i)) for i in range(item.childCount())
            ]
            if item._path:
                # a directory item is right-clicked
                save.setText(_("Save documents in this folder"))
                close.setText(_("Close documents in this folder"))
            else:
                # the "Untitled" group is right-clicked
                save.setText(_("Save all untitled documents"))
                close.setText(_("Close all untitled documents"))

        @save.triggered.connect
        def savedocuments():
            for d in documents:
                if d.url().isEmpty() or d.isModified():
                    mainwindow.setCurrentDocument(d)
                if not mainwindow.saveDocument(d):
                    break

        @close.triggered.connect
        def close_documents():
            for d in documents:
                if not mainwindow.closeDocument(d):
                    break

        menu.exec_(ev.globalPos())
        menu.deleteLater()
Example #5
0
def show(position, panel, link, cursor):
    """Shows a context menu.
    
    position: The global position to pop up
    panel: The music view panel, giving access to mainwindow and view widget
    link: a popplerqt4 LinkBrowse instance or None
    cursor: a QTextCursor instance or None
    
    """
    m = QMenu(panel)

    # selection? -> Copy
    if panel.widget().view.surface().hasSelection():
        m.addAction(panel.actionCollection.music_copy_image)

    if cursor:
        a = m.addAction(icons.get("document-edit"), _("Edit in Place"))

        @a.triggered.connect
        def edit():
            from . import editinplace
            editinplace.edit(panel.widget(), cursor, position)
    elif link:
        a = m.addAction(icons.get("window-new"), _("Open Link in &New Window"))

        @a.triggered.connect
        def open_in_browser():
            import helpers
            helpers.openUrl(QUrl(link.url()))

        a = m.addAction(icons.get("edit-copy"), _("Copy &Link"))

        @a.triggered.connect
        def copy_link():
            QApplication.clipboard().setText(link.url())

    # no actions yet? insert Fit Width/Height
    if not m.actions():
        m.addAction(panel.actionCollection.music_fit_width)
        m.addAction(panel.actionCollection.music_fit_height)
        m.addAction(panel.actionCollection.music_zoom_original)
        m.addSeparator()
        m.addAction(panel.actionCollection.music_sync_cursor)

    # help
    m.addSeparator()
    a = m.addAction(icons.get("help-contents"), _("Help"))

    @a.triggered.connect
    def help():
        import userguide
        userguide.show("musicview")

    # show it!
    if m.actions():
        m.exec_(position)
    m.deleteLater()
Example #6
0
 def contextMenuEvent(self, ev):
     item = self.itemAt(ev.pos())
     if not item:
         return
     
     mainwindow = self.parentWidget().mainwindow()
     
     selection = self.selectedItems()
     doc = self.document(item)
     
     if len(selection) <= 1 and doc:
         # a single document is right-clicked
         import documentcontextmenu
         menu = documentcontextmenu.DocumentContextMenu(mainwindow)
         menu.exec_(doc, ev.globalPos())
         menu.deleteLater()
         return
     
     menu = QMenu(mainwindow)
     save = menu.addAction(icons.get('document-save'), '')
     menu.addSeparator()
     close = menu.addAction(icons.get('document-close'), '')
     
     if len(selection) > 1:
         # multiple documents are selected
         save.setText(_("Save selected documents"))
         close.setText(_("Close selected documents"))
         documents = [self.document(item) for item in selection]
     else:
         documents = [self.document(item.child(i)) for i in range(item.childCount())]
         if item._path:
             # a directory item is right-clicked
             save.setText(_("Save documents in this folder"))
             close.setText(_("Close documents in this folder"))
         else:
             # the "Untitled" group is right-clicked
             save.setText(_("Save all untitled documents"))
             close.setText(_("Close all untitled documents"))
     
     @save.triggered.connect
     def savedocuments():
         for d in documents:
             if d.url().isEmpty() or d.isModified():
                 mainwindow.setCurrentDocument(d)
             if not mainwindow.saveDocument(d):
                 break
     
     @close.triggered.connect
     def close_documents():
         for d in documents:
             if not mainwindow.closeDocument(d):
                 break
     
     menu.exec_(ev.globalPos())
     menu.deleteLater()
Example #7
0
def show(position, panel, link, cursor):
    """Shows a context menu.
    
    position: The global position to pop up
    panel: The music view panel, giving access to mainwindow and view widget
    link: a popplerqt4 LinkBrowse instance or None
    cursor: a QTextCursor instance or None
    
    """
    m = QMenu(panel)
    
    # selection? -> Copy
    if panel.widget().view.surface().hasSelection():
        m.addAction(panel.actionCollection.music_copy_image)
    
    if cursor:
        a = m.addAction(icons.get("document-edit"), _("Edit in Place"))
        @a.triggered.connect
        def edit():
            from . import editinplace
            editinplace.edit(panel.widget(), cursor, position)
    elif link:
        a = m.addAction(icons.get("window-new"), _("Open Link in &New Window"))
        @a.triggered.connect
        def open_in_browser():
            import helpers
            helpers.openUrl(QUrl(link.url()))
        
        a = m.addAction(icons.get("edit-copy"), _("Copy &Link"))
        @a.triggered.connect
        def copy_link():
            QApplication.clipboard().setText(link.url())

    # no actions yet? insert Fit Width/Height
    if not m.actions():
        m.addAction(panel.actionCollection.music_fit_width)
        m.addAction(panel.actionCollection.music_fit_height)
        m.addAction(panel.actionCollection.music_zoom_original)
        m.addSeparator()
        m.addAction(panel.actionCollection.music_sync_cursor)
    
    # help
    m.addSeparator()
    a = m.addAction(icons.get("help-contents"), _("Help"))
    @a.triggered.connect
    def help():
        import userguide
        userguide.show("musicview")
    
    # show it!
    if m.actions():
        m.exec_(position)
    m.deleteLater()
Example #8
0
 def _showContextMenu(self, point):
     index = self.table.indexAt(point)
     if index != None:
         if index.column() != ChatMessagesModel.MESSAGE_COLUMN:
             return
         isOwn = index.data(ChatMessagesModel.OWN_MESSAGE_ROLE).toBool()
         menu = QMenu(self)
         if isOwn:
             menu.addAction(u"Send again", partial(self._sendAgain, index))
         menu.addAction(u"Copy", partial(self._copy, index))
         menu.exec_(QCursor.pos())
         menu.deleteLater()
Example #9
0
class LapigTools:
    def __init__(self, iface):
        self.iface = iface

        self.menu = QMenu("&LAPIG Tools", self.iface.mainWindow().menuBar())
        self.submenu = QMenu("&Time Series Filters")
        self.menu.addMenu(self.submenu)

        self.tools = []
        for key, clazz in tools.__dict__.iteritems():
            if inspect.isclass(clazz) and issubclass(
                    clazz, GenericTool) and key != 'GenericTool':
                self.tools.append(clazz(iface))

    def initGui(self):
        List = []
        ListLabel = []
        for tool in self.tools:
            listA, label = tool.initGui()
            List.append(listA)
            ListLabel.append(label)

        for i in range(len(List)):

            if (ListLabel[i]
                    == 'Savitzky Golay Filter') or (ListLabel[i]
                                                    == 'Hagens Filter'):
                self.submenu.addAction(List[i])
                self.iface.mainWindow().menuBar().insertMenu(
                    List[i], self.menu)
            else:
                self.menu.addAction(List[i])
                self.iface.mainWindow().menuBar().insertMenu(
                    List[i], self.menu)

    def unload(self):
        for tool in self.tools:
            tool.unload()
        self.menu.deleteLater()
Example #10
0
class LapigTools:
	
	def __init__(self, iface):
		self.iface = iface
		
		self.menu = QMenu( "&LAPIG Tools", self.iface.mainWindow().menuBar() )
		self.submenu = QMenu("&Time Series Filters")
		self.menu.addMenu(self.submenu)
		
		self.tools = []
		for key, clazz in tools.__dict__.iteritems():
			if inspect.isclass(clazz) and issubclass(clazz, GenericTool) and key != 'GenericTool':
				self.tools.append(clazz(iface))

	def initGui(self):
		List = []
		ListLabel = []
		for tool in self.tools:
			listA,label = tool.initGui()
			List.append(listA)
			ListLabel.append(label)
				
		for i in range(len(List)):
			
			if (ListLabel[i] == 'Savitzky Golay Filter') or (ListLabel[i] == 'Hagens Filter'):
				self.submenu.addAction(List[i])
				self.iface.mainWindow().menuBar().insertMenu(List[i],self.menu)
			else:	
				self.menu.addAction(List[i])
				self.iface.mainWindow().menuBar().insertMenu(List[i], self.menu)
				
		
	def unload(self):
		for tool in self.tools:
			tool.unload()
		self.menu.deleteLater()	
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 Kortforsyningen:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        self.settings = KFSettings()
        
        path = QFileInfo(os.path.realpath(__file__)).path()
        kf_path = path + '/kf/'
        if not os.path.exists(kf_path):
            os.makedirs(kf_path)
            
        self.settings.addSetting('cache_path', 'string', 'global', kf_path)
        self.settings.addSetting('kf_qlr_url', 'string', 'global', CONFIG_FILE_URL)

        self.local_about_file = kf_path + 'about.html'

        # Categories
        self.categories = []
        self.nodes_by_index = {}
        self.node_count = 0

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
             path,
            'i18n',
            '{}.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.networkManager = QNetworkAccessManager()

    def initGui(self):
        self.config = Config(self.settings, self.networkManager)
        self.config.con_loaded.connect(self.createMenu)
        self.config.kf_con_error.connect(self.show_kf_error)
        self.config.kf_settings_warning.connect(self.show_kf_settings_warning)
        self.config.load()
        
    def show_kf_error(self, error_message):
        log_message(error_message)
        message = u'Check connection and click menu Kortforsyningen->Settings->OK'
        self.iface.messageBar().pushMessage(error_message, message, level=QgsMessageBar.WARNING, duration=10)

    def show_kf_settings_warning(self):
            widget = self.iface.messageBar().createMessage(
                self.tr('Kortforsyningen'), self.tr(u'Username/Password not set or wrong. Click menu Kortforsyningen->Settings')
            )
            settings_btn = QPushButton(widget)
            settings_btn.setText(self.tr("Settings"))
            settings_btn.pressed.connect(self.settings_dialog)
            widget.layout().addWidget(settings_btn)
            self.iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING, duration=10)

    def createMenu(self):
        self.categories = self.config.get_categories()
        self.category_lists = self.config.get_category_lists()
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/Kortforsyningen/settings-cog.png'
        icon_path_info = ':/plugins/Kortforsyningen/icon_about.png'

        self.menu = QMenu(self.iface.mainWindow().menuBar())
        self.menu.setObjectName(self.tr('Kortforsyningen'))
        self.menu.setTitle(self.tr('Kortforsyningen'))
        
        searchable_layers = []

        # Add menu object for each theme
        self.category_menus = []
        kf_helper = lambda _id: lambda: self.open_kf_node(_id)
        local_helper = lambda _id: lambda: self.open_local_node(_id)
        
        for category_list in self.category_lists:
            list_categorymenus = []
            for category in category_list:
                category_menu = QMenu()
                category_menu.setTitle(category['name'])
                for selectable in category['selectables']:
                    q_action = QAction(
                        selectable['name'], self.iface.mainWindow()
                    )
                    if selectable['source'] == 'kf':
                        q_action.triggered.connect(
                            kf_helper(selectable['id'])
                        )
                    else:
                        q_action.triggered.connect(
                            local_helper(selectable['id'])
                        )
                    category_menu.addAction(q_action)
                    searchable_layers.append(
                        {
                            'title': selectable['name'],
                            'category': category['name'],
                            'action': q_action
                        }
                    )
                list_categorymenus.append(category_menu)
                self.category_menus.append(category_menu)
            for category_menukuf in list_categorymenus:
                self.menu.addMenu(category_menukuf)
            self.menu.addSeparator()
        self.septimasearchprovider = MySeptimaSearchProvider(self, searchable_layers)

        # Add settings
        self.settings_menu = QAction(
            QIcon(icon_path),
            self.tr('Settings'),
            self.iface.mainWindow()
        )
        self.settings_menu.setObjectName(self.tr('Settings'))
        self.settings_menu.triggered.connect(self.settings_dialog)
        self.menu.addAction(self.settings_menu)

        # Add about
        self.about_menu = QAction(
            QIcon(icon_path_info),
            self.tr('About the plugin'),
            self.iface.mainWindow()
        )
        self.about_menu.setObjectName(self.tr('About the plugin'))
        self.about_menu.triggered.connect(self.about_dialog)
        self.menu.addAction(self.about_menu)

        menu_bar = self.iface.mainWindow().menuBar()
        menu_bar.insertMenu(
            self.iface.firstRightStandardMenu().menuAction(), self.menu
        )
        
    def open_local_node(self, id):
        node = self.config.get_local_maplayer_node(id)
        self.open_node(node, id)

    def open_kf_node(self, id):
        node = self.config.get_kf_maplayer_node(id)
        layer = self.open_node(node, id)

    def open_node(self, node, id):
        QgsProject.instance().read(node)
        layer = QgsMapLayerRegistry.instance().mapLayer(id)
        if layer:
            self.iface.legendInterface().refreshLayerSymbology(layer)
            #self.iface.legendInterface().moveLayer(layer, 0)
            self.iface.legendInterface().refreshLayerSymbology(layer)
            return layer
        else:
            return None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('Kortforsyningen', message)

    def settings_dialog(self):
        dlg = KFSettingsDialog(self.settings)
        dlg.setWidgetsFromValues()
        dlg.show()
        result = dlg.exec_()

        if result == 1:
            del dlg
            self.reloadMenu()

    def about_dialog(self):
        if 'KFAboutDialog' in globals():
            dlg = KFAboutDialog()
            dlg.webView.setUrl(QUrl(ABOUT_FILE_URL))
            dlg.webView.urlChanged
            dlg.show()
            result = dlg.exec_()

            if result == 1:
                del dlg
        else:
            dlg = KFAlternativeAboutDialog()
            dlg.buttonBox.accepted.connect(dlg.accept)
            dlg.buttonBox.rejected.connect(dlg.reject)
            dlg.textBrowser.setHtml(self.tr('<p>QGIS is having trouble showing the content of this dialog. Would you like to open it in an external browser window?</p>'))
            dlg.show()
            result = dlg.exec_()

            if result:
                webbrowser.open(ABOUT_FILE_URL)

    def unload(self):
        # Remove settings if user not asked to keep them
        if self.settings.value('remember_settings') is False:
            self.settings.setValue('username', '')
            self.settings.setValue('password', '')
        self.clearMenu();
        
    def reloadMenu(self):
        self.clearMenu()
        self.config.load()
        #self.createMenu()
    
    def clearMenu(self):
        # Remove the submenus
        for submenu in self.category_menus:
            if submenu:
                submenu.deleteLater()
        # remove the menu bar item
        if self.menu:
            self.menu.deleteLater()
Example #13
0
class ProcessingPlugin:
    def __init__(self, iface):
        self.iface = iface

    def initGui(self):
        Processing.initialize()

        self.commander = None
        self.toolbox = ProcessingToolbox()
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox)
        self.toolbox.hide()
        Processing.addAlgListListener(self.toolbox)

        self.menu = QMenu(self.iface.mainWindow().menuBar())
        self.menu.setObjectName('processing')
        self.menu.setTitle(self.tr('Pro&cessing'))

        self.toolboxAction = self.toolbox.toggleViewAction()
        self.toolboxAction.setObjectName('toolboxAction')
        self.toolboxAction.setIcon(
            QIcon(os.path.join(cmd_folder, 'images', 'alg.png')))
        self.toolboxAction.setText(self.tr('&Toolbox'))
        self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T')
        self.menu.addAction(self.toolboxAction)

        self.modelerAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'model.png')),
            self.tr('Graphical &Modeler...'), self.iface.mainWindow())
        self.modelerAction.setObjectName('modelerAction')
        self.modelerAction.triggered.connect(self.openModeler)
        self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M')
        self.menu.addAction(self.modelerAction)

        self.historyAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'history.gif')),
            self.tr('&History...'), self.iface.mainWindow())
        self.historyAction.setObjectName('historyAction')
        self.historyAction.triggered.connect(self.openHistory)
        self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H')
        self.menu.addAction(self.historyAction)

        self.configAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'config.png')),
            self.tr('&Options...'), self.iface.mainWindow())
        self.configAction.setObjectName('configAction')
        self.configAction.triggered.connect(self.openConfig)
        self.iface.registerMainWindowAction(self.configAction, 'Ctrl+Alt+C')
        self.menu.addAction(self.configAction)

        self.resultsAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'results.png')),
            self.tr('&Results Viewer...'), self.iface.mainWindow())
        self.resultsAction.setObjectName('resultsAction')
        self.resultsAction.triggered.connect(self.openResults)
        self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R')
        self.menu.addAction(self.resultsAction)

        menuBar = self.iface.mainWindow().menuBar()
        menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(),
                           self.menu)

        self.commanderAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'commander.png')),
            self.tr('&Commander'), self.iface.mainWindow())
        self.commanderAction.setObjectName('commanderAction')
        self.commanderAction.triggered.connect(self.openCommander)
        self.menu.addAction(self.commanderAction)
        self.iface.registerMainWindowAction(self.commanderAction,
                                            self.tr('Ctrl+Alt+M'))

    def unload(self):
        self.toolbox.setVisible(False)
        self.menu.deleteLater()

        # delete temporary output files
        folder = tempFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        self.iface.unregisterMainWindowAction(self.commanderAction)

    def openCommander(self):
        if self.commander is None:
            self.commander = CommanderWindow(self.iface.mainWindow(),
                                             self.iface.mapCanvas())
            Processing.addAlgListListener(self.commander)
        self.commander.prepareGui()
        self.commander.show()

    def openToolbox(self):
        if self.toolbox.isVisible():
            self.toolbox.hide()
        else:
            self.toolbox.show()

    def openModeler(self):
        dlg = ModelerDialog()
        dlg.show()
        dlg.exec_()
        if dlg.update:
            self.toolbox.updateProvider('model')

    def openResults(self):
        dlg = ResultsDialog()
        dlg.show()
        dlg.exec_()

    def openHistory(self):
        dlg = HistoryDialog()
        dlg.exec_()

    def openConfig(self):
        dlg = ConfigDialog(self.toolbox)
        dlg.exec_()

    def tr(self, message):
        return QCoreApplication.translate('ProcessingPlugin', message)
Example #14
0
class ProcessingPlugin:

    def __init__(self, iface):
        self.iface = iface

    def initGui(self):
        Processing.initialize()

        self.commander = None
        self.toolbox = ProcessingToolbox()
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox)
        self.toolbox.hide()
        Processing.addAlgListListener(self.toolbox)

        self.menu = QMenu(self.iface.mainWindow().menuBar())
        self.menu.setObjectName('processing')
        self.menu.setTitle(self.tr('Pro&cessing'))

        self.toolboxAction = self.toolbox.toggleViewAction()
        self.toolboxAction.setObjectName('toolboxAction')
        self.toolboxAction.setIcon(
            QIcon(os.path.join(cmd_folder, 'images', 'alg.png')))
        self.toolboxAction.setText(self.tr('&Toolbox'))
        self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T')
        self.menu.addAction(self.toolboxAction)

        self.modelerAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'model.png')),
            self.tr('Graphical &Modeler...'), self.iface.mainWindow())
        self.modelerAction.setObjectName('modelerAction')
        self.modelerAction.triggered.connect(self.openModeler)
        self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M')
        self.menu.addAction(self.modelerAction)

        self.historyAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'history.gif')),
            self.tr('&History...'), self.iface.mainWindow())
        self.historyAction.setObjectName('historyAction')
        self.historyAction.triggered.connect(self.openHistory)
        self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H')
        self.menu.addAction(self.historyAction)

        self.configAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'config.png')),
            self.tr('&Options...'), self.iface.mainWindow())
        self.configAction.setObjectName('configAction')
        self.configAction.triggered.connect(self.openConfig)
        self.iface.registerMainWindowAction(self.configAction, 'Ctrl+Alt+C')
        self.menu.addAction(self.configAction)

        self.resultsAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'results.png')),
            self.tr('&Results Viewer...'), self.iface.mainWindow())
        self.resultsAction.setObjectName('resultsAction')
        self.resultsAction.triggered.connect(self.openResults)
        self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R')
        self.menu.addAction(self.resultsAction)

        menuBar = self.iface.mainWindow().menuBar()
        menuBar.insertMenu(
            self.iface.firstRightStandardMenu().menuAction(), self.menu)

        self.commanderAction = QAction(
            QIcon(os.path.join(cmd_folder, 'images', 'commander.png')),
            self.tr('&Commander'), self.iface.mainWindow())
        self.commanderAction.setObjectName('commanderAction')
        self.commanderAction.triggered.connect(self.openCommander)
        self.menu.addAction(self.commanderAction)
        self.iface.registerMainWindowAction(self.commanderAction,
                                            self.tr('Ctrl+Alt+M'))

    def unload(self):
        self.toolbox.setVisible(False)
        self.menu.deleteLater()

        # delete temporary output files
        folder = tempFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        self.iface.unregisterMainWindowAction(self.commanderAction)

    def openCommander(self):
        if self.commander is None:
            self.commander = CommanderWindow(
                self.iface.mainWindow(),
                self.iface.mapCanvas())
            Processing.addAlgListListener(self.commander)
        self.commander.prepareGui()
        self.commander.show()

    def openToolbox(self):
        if self.toolbox.isVisible():
            self.toolbox.hide()
        else:
            self.toolbox.show()

    def openModeler(self):
        dlg = ModelerDialog()
        dlg.show()
        dlg.exec_()
        if dlg.update:
            self.toolbox.updateProvider('model')

    def openResults(self):
        dlg = ResultsDialog()
        dlg.show()
        dlg.exec_()

    def openHistory(self):
        dlg = HistoryDialog()
        dlg.exec_()

    def openConfig(self):
        dlg = ConfigDialog(self.toolbox)
        dlg.exec_()

    def tr(self, message):
        return QCoreApplication.translate('ProcessingPlugin', message)
Example #15
0
class Main(object):
    def __init__(self, iface):
        self.iface = iface

    def initGui(self):
        self.siteStyle = False  # 用于判断是否对小区图层进行额外渲染
        self.cellStyle = False  # 用于判断是否对小区图层进行额外渲染
        self.cellStyleManager = None  # 小区样式管理器
        self._styleManager = None  # 任意图层样式管理器
        self.radius = "10.000"  # 默认渲染半径
        self.quality = 2  # 默认渲染质量
        self.mainWindow = self.iface.mainWindow()

        self.myMenu = QMenu(u'&移动通信规划功能', self.mainWindow)
        '''新建工程按钮'''
        initPorjectAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'imp.png')), u'新建工程',
            self.mainWindow)
        QObject.connect(initPorjectAction, SIGNAL('triggered()'),
                        self.initProjectFunc)
        '''数据导入菜单'''
        DataMenu = QMenu(u'&数据处理', self.mainWindow)
        importAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'imp.png')), u'数据导入',
            self.mainWindow)
        QObject.connect(importAction, SIGNAL('triggered()'), self.importFunc)
        exportActoin = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'export.jpg')), u'数据导出',
            self.mainWindow)
        QObject.connect(exportActoin, SIGNAL('triggered()'), self.exportFunc)
        createModelAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'create.png')),
            u'生成Excel模板', self.mainWindow)
        QObject.connect(createModelAction, SIGNAL('triggered()'),
                        self.createModelFunc)
        # 从子菜单中添加功能按钮
        DataMenu.addAction(importAction)
        DataMenu.addAction(exportActoin)
        DataMenu.addAction(createModelAction)
        '''基站布点'''
        SiteMenu = QMenu(u'&基站布点', self.mainWindow)

        addSiteAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'add.png')), u'添加基站  ',
            self.mainWindow)
        addSiteAction.triggered.connect(self.addSiteFunc)
        addCellAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'addcell.png')),
            u'添加小区  ', self.mainWindow)
        addCellAction.triggered.connect(self.addCellFunc)
        moveSiteAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'move.png')), u'移动基站  ',
            self.mainWindow)
        moveSiteAction.triggered.connect(self.moveSiteFunc)
        delSiteAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'remove.png')),
            u'删除基站小区  ', self.mainWindow)
        delSiteAction.triggered.connect(self.delSiteFunc)
        modifyAzimuthAction = QAction(u'修改小区方向角 ', self.mainWindow)
        QObject.connect(modifyAzimuthAction, SIGNAL('triggered()'),
                        self.modifyAzimuthFunc)
        searchSiteAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'find.png')),
            u'查找基站小区  ', self.mainWindow)
        searchSiteAction.triggered.connect(self.searchFunc)

        SiteMenu.addAction(addSiteAction)
        SiteMenu.addAction(addCellAction)
        SiteMenu.addAction(moveSiteAction)
        SiteMenu.addAction(delSiteAction)
        SiteMenu.addAction(modifyAzimuthAction)
        SiteMenu.addAction(searchSiteAction)
        '''相邻小区'''
        NCellMenu = QMenu(u'&相邻小区', self.mainWindow)

        showNCellAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'设置相邻小区.png')),
            u'设置服务小区并显示其相邻小区  ', self.mainWindow)
        QObject.connect(showNCellAction, SIGNAL('triggered()'),
                        self.showNCellFunc)
        addNCell1Action = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'增加单向邻区.png')),
            u'增加单向相邻小区  ', self.mainWindow)
        QObject.connect(addNCell1Action, SIGNAL('triggered()'),
                        self.addOneWayNCellFunc)
        addNCell2Action = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'增加双向邻区.png')),
            u'增加双向相邻小区  ', self.mainWindow)
        QObject.connect(addNCell2Action, SIGNAL('triggered()'),
                        self.addTwoWayNCellFunc)
        delNCellAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'删除邻区.jpg')),
            u'删除相邻小区  ', self.mainWindow)
        QObject.connect(delNCellAction, SIGNAL('triggered()'),
                        self.delNCellFunc)
        checkRepeatAction = QAction(u'检查相邻小区的重复性,并自动修正  ', self.mainWindow)
        QObject.connect(checkRepeatAction, SIGNAL('triggered()'),
                        self.checkRepeatFunc)
        #保存选中的服务小区(列表中存string)
        self.SCell_list = []
        self.HL_SCell = None  # 当前的高亮显示的主服务小区
        self.HL_NCell_O = []  # 高亮显示的单向邻区list
        self.HL_NCell_D = []  # 高亮显示的双向邻区list

        NCellMenu.addAction(showNCellAction)
        NCellMenu.addSeparator()
        NCellMenu.addAction(addNCell1Action)
        NCellMenu.addAction(addNCell2Action)
        NCellMenu.addAction(delNCellAction)
        NCellMenu.addAction(checkRepeatAction)
        '''网优分析'''
        NetAnalysisMenu = QMenu(u'&网优分析', self.mainWindow)

        mod3Action = QAction(u'模三分析 ', self.mainWindow)
        QObject.connect(mod3Action, SIGNAL('triggered()'), self.mod3Func)
        createRenderAction = QAction(u'生成渲染图 ', self.mainWindow)
        QObject.connect(createRenderAction, SIGNAL('triggered()'),
                        self.createRenderFunc)
        updatePolygonAction = QAction(u'更新区域信息 ', self.mainWindow)
        QObject.connect(updatePolygonAction, SIGNAL('triggered()'),
                        self.updatePolygonInfoFunc)
        rangeByNoAction = QAction(u'按范围分类显示(针对数字)', self.mainWindow)
        QObject.connect(rangeByNoAction, SIGNAL('triggered()'),
                        self.rangeByNoFunc)
        rangeByStrAction = QAction(u'按类别分类显示(针对字符)', self.mainWindow)
        QObject.connect(rangeByStrAction, SIGNAL('triggered()'),
                        self.rangeByStrFunc)

        NetAnalysisMenu.addAction(mod3Action)
        NetAnalysisMenu.addAction(createRenderAction)
        NetAnalysisMenu.addAction(updatePolygonAction)
        NetAnalysisMenu.addAction(rangeByNoAction)
        NetAnalysisMenu.addAction(rangeByStrAction)
        '''基站规划分析'''
        SiteAnalysisMenu = QMenu(u'&基站规划分析', self.mainWindow)

        AutoBuildSiteAction = QAction(u'自动规划基站', self.mainWindow)
        QObject.connect(AutoBuildSiteAction, SIGNAL('triggered()'),
                        self.AutoBuildSiteFunc)
        addCandidateSiteAction = QAction(u'添加待选站点', self.mainWindow)
        QObject.connect(addCandidateSiteAction, SIGNAL('triggered()'),
                        self.addCandidateSiteFunc)
        quickPCIAction = QAction(u'快速PCI规划', self.mainWindow)
        QObject.connect(quickPCIAction, SIGNAL('triggered()'),
                        self.quickPCIFunc)
        accuratePCIAction = QAction(u'精确PCI规划', self.mainWindow)
        QObject.connect(accuratePCIAction, SIGNAL('triggered()'),
                        self.accuratePCIFunc)

        SiteAnalysisMenu.addAction(AutoBuildSiteAction)
        SiteAnalysisMenu.addAction(addCandidateSiteAction)
        # SiteAnalysisMenu.addAction(quickPCIAction)
        # SiteAnalysisMenu.addAction(accuratePCIAction)
        '''网络地图'''
        OnlineMapMenu = QMenu(u"网络地图", self.mainWindow)

        createKMLAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'kml_file.ico')),
            u'生成KML图层 ', self.mainWindow)
        QObject.connect(createKMLAction, SIGNAL('triggered()'),
                        self.createKMLFunc)
        # 生成百度html
        createBaiduMapAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'Baidu.png')),
            u'导出到百度地图 ', self.mainWindow)
        QObject.connect(createBaiduMapAction, SIGNAL('triggered()'),
                        self.createBaiduMapFunc)
        # 生成腾讯html
        createTencentMapAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'Tencent.png')),
            u'导出到腾讯地图 ', self.mainWindow)
        QObject.connect(createTencentMapAction, SIGNAL('triggered()'),
                        self.createTencentMapFunc)
        # 生成搜狗html
        createSogotMapAction = QAction(
            QIcon(os.path.join(cmd_folder, u'images', u'Sogo.png')),
            u'导出到搜狗地图 ', self.mainWindow)
        QObject.connect(createSogotMapAction, SIGNAL('triggered()'),
                        self.createSogotMapFunc)
        # 从百度地图抓取相关热点
        searchPOIAction = QAction(u'从百度地图抓取相关热点', self.mainWindow)
        QObject.connect(searchPOIAction, SIGNAL('triggered()'),
                        self.searchPOIFunc)

        OnlineMapMenu.addAction(createKMLAction)
        OnlineMapMenu.addAction(createBaiduMapAction)
        OnlineMapMenu.addAction(createTencentMapAction)
        OnlineMapMenu.addAction(createSogotMapAction)
        OnlineMapMenu.addAction(searchPOIAction)
        '''帮助功能'''
        HelpAction = QAction(u'帮助', self.mainWindow)
        QObject.connect(HelpAction, SIGNAL('triggered()'), self.HelpFunc)

        # 整合功能菜单
        self.myMenu.addAction(initPorjectAction)
        self.myMenu.addMenu(DataMenu)
        self.myMenu.addMenu(SiteMenu)
        self.myMenu.addMenu(NCellMenu)
        self.myMenu.addMenu(NetAnalysisMenu)
        self.myMenu.addMenu(SiteAnalysisMenu)
        self.myMenu.addMenu(OnlineMapMenu)
        self.myMenu.addAction(HelpAction)

        #pluginM = self.iface.pluginMenu()
        #pluginM.addMenu(self.myMenu)

        # 向菜单栏中添加插件菜单
        menuBar = self.mainWindow.menuBar()
        self.m = menuBar.addMenu(u'&移动通信规划功能')
        self.m.addAction(initPorjectAction)
        self.m.addMenu(DataMenu)
        self.m.addMenu(SiteMenu)
        self.m.addMenu(NCellMenu)
        self.m.addMenu(NetAnalysisMenu)
        self.m.addMenu(SiteAnalysisMenu)
        self.m.addMenu(OnlineMapMenu)
        self.m.addAction(HelpAction)

    # remove the plugin menu item and icon
    def unload(self):
        self.myMenu.deleteLater()
        self.m.deleteLater()

    #新建工程
    def initProjectFunc(self):
        dlg = InitProjectDlg(self.iface, self.mainWindow)
        dlg.show()
        dlg.exec_()

    #导入数据
    def importFunc(self):
        # 判断是否已初始化工程
        if not judgeInitProject(self.iface):
            QMessageBox.critical(self.mainWindow, u"错误", u"请先初始化工程!")
            return
        else:
            dlg = ImportDataDlg(self.iface, self.mainWindow)
            dlg.show()
            dlg.exec_()

    #导出数据
    def exportFunc(self):
        dlg = ExportDataUI(self.iface, self.mainWindow)
        dlg.show()

    #生成模板文件
    def createModelFunc(self):
        dlg = CreateModelDlg(self.iface, self.mainWindow)
        dlg.show()

    # 向基站图层中添加基站
    def addSiteFunc(self):
        ui = AddSiteUI(self.iface, self.mainWindow)
        ui.show()
        ui.exec_()

    #选中基站后在小区图层中向其添加捆绑小区
    def addCellFunc(self):
        # 先判断有没有只选中1个基站
        if isSelectedASite(self.iface):
            ui = AddCellUI(self.iface, self.mainWindow)
            ui.show()
            ui.exec_()
        else:
            QMessageBox.critical(self.mainWindow, u"提示",
                                 u"请在基站图层上选中1个要添加小区的基站")

    # 移动基站
    def moveSiteFunc(self):
        # 判断是否只选中了一个基站
        if isSelectedASite(self.iface):
            ui = MoveSiteUI(self.iface, self.mainWindow)
            ui.show()
            ui.exec_()
        else:
            QMessageBox.critical(self.mainWindow, u"提示",
                                 u"请在基站图层上选中1个要添加小区的基站")

    # 删除基站和小区
    def delSiteFunc(self):
        ui = DeleteSiteUI(self.iface, self.mainWindow)

    # 修改小区方向
    def modifyAzimuthFunc(self):
        ui = ModifyAzimuthUI(self.iface, self.mainWindow)
        ui.show()
        ui.exec_()

    # 查找基站小区
    def searchFunc(self):
        ui = SearchUI(self.iface, self.mainWindow)
        ui.show()
        ui.exec_()

    # 设置服务小区并显示其相邻小区
    def showNCellFunc(self):
        self.SCell_list, self.HL_SCell = getSCell(self.iface, self.HL_SCell,
                                                  self.mainWindow)
        # 判断选中的服务小区是否唯一
        if len(self.SCell_list) == 0:
            QMessageBox.critical(self.mainWindow, u"错误", u"请先设置服务小区!")
            return
        elif len(self.SCell_list) > 1:
            QMessageBox.critical(self.mainWindow, u"错误", u"只能选择一个小区作为服务小区!")
            return
        else:
            showSCell = SCellControls(self.iface, self.SCell_list[0],
                                      self.HL_NCell_O, self.HL_NCell_D)
            showSCell.showCellFeature()

    # 增加单向相邻小区
    def addOneWayNCellFunc(self):
        addOneWaySCell(self.iface, self.SCell_list)

    # 增加双向相邻小区
    def addTwoWayNCellFunc(self):
        addTwoWaySCell(self.iface, self.SCell_list)

    # 删除选中的相邻小区
    def delNCellFunc(self):
        ui = DeleteNCellUI(self.iface, self.SCell_list, self.mainWindow)
        ui.show()
        ui.exec_()

    # 检查相邻小区的重复性,并自动修正
    def checkRepeatFunc(self):
        controls = SCellControls(self.iface)
        controls.checkRepeat()

    # 模三分析
    def mod3Func(self):
        if not self.cellStyle:
            # 如果没有对小区图层进行额外渲染
            cellLayer = getLayerByName(u"小区", self.iface)
            # 判断是否存在cellLayer
            if not cellLayer:
                QMessageBox.critical(self.mainWindow, u"错误",
                                     u"找不到小区图层, 请检查是否已初始化工程!")
                return
            self.cellStyleManager = QgsMapLayerStyleManager(cellLayer)
            self.cellStyleManager.addStyleFromLayer(u'默认')
        Mod3Render(self.iface, self.cellStyleManager, self.mainWindow)

    # 生成热力渲染图
    def createRenderFunc(self):
        # 判断是否对基站图层进行过额外渲染
        # if self.siteStyle:
        #     self.siteStyle, self.radius, self.quality = setDeafaultRender(self.iface, self._styleManager)
        self.siteStyle, self.radius, self.quality = HeatRender(
            self.iface, self.siteStyle, self.radius, self.quality,
            self.mainWindow)

    # 向基站和进小区图层的相应字段添加选中Polygon属性
    def updatePolygonInfoFunc(self):
        layer = self.iface.activeLayer()
        if not layer:
            QMessageBox.critical(self.mainWindow, u'错误',
                                 u'<b>请选择要添加的Polygon图层<\b>')
        elif (layer.name() in [u"基站", u"小区", u"相邻小区"]):
            QMessageBox.critical(self.mainWindow, u'错误',
                                 u'<b>请选择要添加的Polygon图层<\b>')
        else:
            polygon = UpdatePolygonInfoUI(self.iface, self.mainWindow)
            polygon.show()
            polygon.exec_()

    # 按范围分类显示(针对数字)
    def rangeByNoFunc(self):
        ui = RangeByNoSettingUI(self.iface, self.mainWindow)
        ui.show()
        ui.exec_()

    # 按类别分类显示(针对字符)
    def rangeByStrFunc(self):
        ui = RangeByStrSettingUI(self.iface, self.mainWindow)
        ui.show()
        ui.exec_()

    # 自动规划基站
    def AutoBuildSiteFunc(self):
        dlg = AutoBuildSiteSettingDlg(self.iface, self.mainWindow)
        dlg.show()
        dlg.exec_()

    # 添加待选站点
    def addCandidateSiteFunc(self):
        add = AddNSitesUI(self.iface, self.mainWindow)
        add.show()
        add.exec_()

    # 快速PCI规划
    def quickPCIFunc(self):
        dlg = QuickPCISettingDlg(self.iface, self.mainWindow)
        dlg.show()
        dlg.exec_()

    # 精确PCI规划
    def accuratePCIFunc(self):
        dlg = AccuratePCISettingDlg(self.iface, self.mainWindow)
        dlg.show()
        dlg.exec_()

    # 生成KML图层
    def createKMLFunc(self):
        expKML = ExportDataToKMLUI(self.iface, self.mainWindow)
        expKML.show()
        expKML.exec_()

    # 导出站点到百度地图
    def createBaiduMapFunc(self):
        expBaidu = ExportDataToBaiduUI(self.iface, self.mainWindow)
        expBaidu.show()
        expBaidu.exec_()

    # 导出站点到腾讯地图
    def createTencentMapFunc(self):
        expTencent = ExportDataToTencentUI(self.iface, self.mainWindow)
        expTencent.show()
        expTencent.exec_()

    # 导出站点到搜狗地图
    def createSogotMapFunc(self):
        expSogo = ExportDataToSogoUI(self.iface, self.mainWindow)
        expSogo.show()
        expSogo.exec_()

    # 从百度地图中抓取地理信息
    def searchPOIFunc(self):
        ui = SearchPOIFromBaiduUI(self.iface, self.mainWindow)
        ui.show()
        ui.exec_()

    # 弹出帮助文档
    def HelpFunc(self):
        doc_path = os.path.join(cmd_folder, u"移动通信网络规划功能帮助文档.pdf")
        if os.path.exists(doc_path):
            os.startfile(doc_path)
        else:
            QMessageBox.critical(self.mainWindow, u"错误", u"帮助文档不存在,请联系管理员!")
Example #16
0
 def contextMenuEvent(self, ev):
     m = QMenu(self)
     a = m.addAction(_("Configure Keyboard Shortcut ({key})").format(key = self.key() or _("None")))
     a.triggered.connect(self.editShortcut)
     m.exec_(ev.globalPos())
     m.deleteLater()
Example #17
0
class Historize(QObject):
    """This class handles the initialization and calls of the menus"""
    def __init__(self, iface):
        QObject.__init__(self)

        self.iface = iface
        self.dbconn = DBConn(iface)
        plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(plugin_dir, 'i18n',
                                   'Historize_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            translator = QTranslator()
            translator.load(locale_path)
            QCoreApplication.installTranslator(translator)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(translator)

    def initGui(self):
        self.menu = QMenu()
        self.menu.setTitle("Historize")

        self.layerMenu = QMenu()
        self.layerMenu.setTitle("Layer")

        # Create menu actions
        self.actionInitDB = QAction(self.tr(u"Initialize Database"),
                                    self.iface.mainWindow())
        self.actionInitLayer = QAction(self.tr(u"Initialize Layer"),
                                       self.iface.mainWindow())
        self.actionLayerUpdate = QAction(self.tr(u"Update Layer"),
                                         self.iface.mainWindow())
        self.actionLayerLoad = QAction(self.tr(u"Load Layer"),
                                       self.iface.mainWindow())
        self.actionAbout = QAction(self.tr(u"About"), self.iface.mainWindow())

        # Connect menu actions
        self.actionInitDB.triggered.connect(self.initialize_database)
        self.actionInitLayer.triggered.connect(self.initialize_layer)
        self.actionLayerLoad.triggered.connect(self.show_load_layer_dialog)
        self.actionLayerUpdate.triggered.connect(self.show_update_layer_dialog)
        self.actionAbout.triggered.connect(self.show_about_dialog)

        self.iface.legendInterface().currentLayerChanged.connect(
            self.enable_disable_gui)

        # Add actions to menu
        self.layerMenu.addActions([
            self.actionInitLayer, self.actionLayerLoad, self.actionLayerUpdate
        ])
        self.menu.addAction(self.actionInitDB)
        self.menu.addMenu(self.layerMenu)
        self.menu.addAction(self.actionAbout)
        self.menu.insertSeparator(self.actionAbout)
        menuBar = self.iface.mainWindow().menuBar()
        menuBar.addMenu(self.menu)

        # Disable unusable actions
        self.actionInitDB.setEnabled(False)
        self.actionInitLayer.setEnabled(False)
        self.actionLayerUpdate.setEnabled(False)
        self.actionLayerLoad.setEnabled(False)

    def unload(self):
        self.menu.deleteLater()

    def initialize_database(self):
        """Use Database info from layer and run historisation.sql on it."""

        selectedLayer = self.iface.activeLayer()
        provider = selectedLayer.dataProvider()

        if provider.name() != 'postgres':
            QMessageBox.warning(
                self.iface.mainWindow(), self.tr(u"Invalid Layer"),
                self.tr(u"Layer must be provided by postgres!"))
            return
        uri = QgsDataSourceURI(provider.dataSourceUri())
        conn = self.dbconn.connect_to_DB(uri)
        cur = conn.cursor()
        if conn is False:
            return

        result = QMessageBox.warning(
            self.iface.mainWindow(), self.tr(u"Initialize Historisation"),
            self.tr(u"Initialize historisation on this layers database?"),
            QMessageBox.No | QMessageBox.Yes)
        if result == QMessageBox.Yes:
            sqlPath = os.path.dirname(
                os.path.realpath(__file__)) + '/sql/historisierung.sql'
            try:
                # Ignore first three characters
                # which invalidate the SQL command
                cur.execute(open(sqlPath, "r").read())
                conn.commit()
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Success"),
                    self.tr(u"Database initialized successfully!"))
            except psycopg2.Error as e:
                conn.rollback()
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Error"),
                    self.tr(u"Couldn't initialize Database.\n" + e.message))
            conn.close()
            self.enable_disable_gui(selectedLayer)
        else:
            return

    def initialize_layer(self):
        """Use Layer info and run init() .sql query"""
        selectedLayer = self.iface.activeLayer()
        provider = selectedLayer.dataProvider()
        uri = QgsDataSourceURI(provider.dataSourceUri())
        conn = self.dbconn.connect_to_DB(uri)

        if conn is False:
            return

        result = QMessageBox.warning(
            self.iface.mainWindow(), self.tr(u"Initialize Layer"),
            self.tr(u"Are you sure you wish to proceed?"),
            QMessageBox.No | QMessageBox.Yes)
        if result == QMessageBox.Yes:
            # Get SQL vars
            hasGeometry = selectedLayer.hasGeometryType()
            schema = uri.schema()
            table = uri.table()

            execute = SQLExecute(self.iface, self.iface.mainWindow(), uri)
            success, msg = execute.Init_hist_tabs(hasGeometry, schema, table)
            if success:
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr(u"Success"),
                    self.tr(u"Layer successfully initialized!"))
            else:
                QMessageBox.warning(self.iface.mainWindow(), self.tr(u"Error"),
                                    self.tr(u"Initialization failed!\n" + msg))
            self.enable_disable_gui(selectedLayer)
        else:
            return

    def show_update_layer_dialog(self):
        """Open ImportUpdate dialog"""
        self.updateDialog = ImportUpdateDialog(self.iface)
        self.updateDialog.show()

    def show_load_layer_dialog(self):
        """Open selectDate dialog"""
        self.dateDialog = SelectDateDialog(self.iface)
        self.dateDialog.show()

    def show_about_dialog(self):
        """Show About dialog"""
        self.aboutDialog = AboutDialog()
        self.aboutDialog.show()

    def enable_disable_gui(self, layer):
        """Enable/Disable menu options based on selected layer"""
        self.actionInitDB.setEnabled(False)
        self.layerMenu.setEnabled(False)
        self.actionInitLayer.setEnabled(False)
        self.actionLayerUpdate.setEnabled(False)
        self.actionLayerLoad.setEnabled(False)

        selectedLayer = self.iface.activeLayer()
        if selectedLayer:
            provider = layer.dataProvider()

            if provider.name() == "postgres":
                self.actionInitDB.setEnabled(True)
                uri = QgsDataSourceURI(provider.dataSourceUri())
                execute = SQLExecute(self.iface, self.iface.mainWindow(), uri)
                historised = execute.check_if_historised(
                    uri.schema(),
                    self.iface.activeLayer().name())
                db_initialized = execute.db_initialize_check(uri.schema())

                if db_initialized:
                    self.actionInitDB.setEnabled(False)
                    self.layerMenu.setEnabled(True)
                else:
                    self.layerMenu.setEnabled(False)

                if historised:
                    self.actionLayerUpdate.setEnabled(True)
                    self.actionLayerLoad.setEnabled(True)
                else:
                    self.actionInitLayer.setEnabled(True)