def qgis_iface_menu(qgis_iface: QgisInterface) -> QgisInterface:
    menu: QMenu = qgis_iface.mainWindow().menuBar()
    """
    Add menus to the QgisInterface. By default, the interface mock create only an empty menu.

    :param qgis_iface: The mocked interface provided by the qgis-pytest fixtures
    :type qgis_iface: QgisInterface
    :return: The same QgisInterface mock with three menus in the menu bar
    :rtype: QgisInterface
    """
    menu_a: QMenu = QMenu('A', menu)
    menu_b: QMenu = QMenu('B', menu)
    menu_c: QMenu = QMenu('C', menu)
    menu.addMenu(menu_a)
    menu.addMenu(menu_b)
    menu.addMenu(menu_c)

    yield qgis_iface

    qgis_iface.mainWindow().menuBar().removeAction(menu_a.menuAction())
    qgis_iface.mainWindow().menuBar().removeAction(menu_b.menuAction())
    qgis_iface.mainWindow().menuBar().removeAction(menu_c.menuAction())
    menu_a.deleteLater()
    menu_b.deleteLater()
    menu_c.deleteLater()
Exemplo n.º 2
0
 def __init__(self, iface: QgisInterface, layer):
     QgsMapToolAdvancedDigitizing.__init__(self, iface.mapCanvas(), iface.cadDockWidget())
     self.iface = iface
     self.canvas = iface.mapCanvas()
     self.layer = layer
     self.rubberband = QgepRubberBand3D(iface.mapCanvas(), layer.geometryType())
     self.rubberband.setColor(QColor("#ee5555"))
     self.rubberband.setWidth(1)
     self.temp_rubberband = QgsRubberBand(iface.mapCanvas(), layer.geometryType())
     self.temp_rubberband.setColor(QColor("#ee5555"))
     self.temp_rubberband.setWidth(1)
     self.temp_rubberband.setLineStyle(Qt.DotLine)
Exemplo n.º 3
0
    def __init__(self,
                 data: dict,
                 iface: QgisInterface,
                 is_background: bool,
                 alternate_mode: bool = False):

        # debug
        for i, v in data.items():
            if i in ('qml', 'contacts'): continue
            if i == 'sublayers':
                for sublayer in data['sublayers']:
                    for j, u in sublayer.items():
                        if j in ('qml', 'contacts'): continue
                        dbg_info('*** sublayer {}: {}'.format(j, u))
            else:
                dbg_info('*** {}: {}'.format(i, v))

        data = self.reformat_data(data)

        settings = Settings()
        loading_mode: LoadingMode = settings.value(
            'default_layer_loading_mode')
        if alternate_mode:
            loading_mode = loading_mode.alternate_mode()

        if is_background:
            loading_mode = LoadingMode.WMS
            root = iface.layerTreeView().model().rootGroup()
            pos = len(root.children())
            insertion_point = InsertionPoint(root, pos)

        else:
            try:
                insertion_point = iface.layerTreeInsertionPoint()
            except AttributeError:
                # backward compatibility for QGIS < 3.10
                # TODO: remove
                insertion_point = layerTreeInsertionPoint(
                    iface.layerTreeView())

        dbg_info("insertion point: {} {}".format(insertion_point.group.name(),
                                                 insertion_point.position))

        loading_options = LoadingOptions(
            wms_load_separate=settings.value('wms_load_separate'),
            wms_image_format=settings.value('wms_image_format'),
            loading_mode=loading_mode,
            pg_auth_id=settings.value('pg_auth_id'),
            pg_service=settings.value('pg_service'))

        data.load(insertion_point, loading_options)
Exemplo n.º 4
0
    def __init__(self, iface: QgisInterface, button, network_analyzer: QgepGraphManager = None):
        QgsMapTool.__init__(self, iface.mapCanvas())
        self.canvas = iface.mapCanvas()
        self.cursor = QCursor(Qt.CrossCursor)
        self.button = button
        self.msgBar = iface.messageBar()
        self.network_analyzer = network_analyzer

        settings = QSettings()
        current_profile_color = settings.value(
            "/QGEP/CurrentProfileColor", '#FF9500')

        self.rubberBand = QgsRubberBand(self.canvas)
        self.rubberBand.setColor(QColor(current_profile_color))
        self.rubberBand.setWidth(3)
Exemplo n.º 5
0
    def __init__(self, iface: QgisInterface = None):
        """"
        :param iface: QGIS interface, given when on the main thread (which will display/trigger results), None otherwise
        """
        super().__init__()

        self.iface = iface
        self.settings = Settings()

        #  following properties will only be used in main thread
        self.rubber_band = None
        self.map_canvas: QgsMapCanvas = None
        self.transform_ch = None
        self.current_timer = None
        self.result_found = False
        self.nam_fetch_feature = None

        if iface is not None:
            # happens only in main thread
            self.map_canvas = iface.mapCanvas()
            self.map_canvas.destinationCrsChanged.connect(
                self.create_transforms)

            self.rubber_band = QgsRubberBand(
                self.map_canvas, QgsWkbTypes.PolygonGeometry)
            self.rubber_band.setColor(QColor(255, 50, 50, 200))
            self.rubber_band.setFillColor(QColor(255, 255, 50, 160))
            self.rubber_band.setBrushStyle(Qt.SolidPattern)
            self.rubber_band.setLineStyle(Qt.SolidLine)
            self.rubber_band.setIcon(self.rubber_band.ICON_CIRCLE)
            self.rubber_band.setIconSize(15)
            self.rubber_band.setWidth(4)
            self.rubber_band.setBrushStyle(Qt.NoBrush)

            self.create_transforms()
    def __init__(self,
                 filter_type: FilterType,
                 iface: QgisInterface = None,
                 crs: str = None):
        """"
        :param filter_type: the type of filter
        :param locale_lang: the language of the locale.
        :param iface: QGIS interface, given when on the main thread (which will display/trigger results), None otherwise
        :param crs: if iface is not given, it shall be provided, see clone()
        """
        super().__init__()
        self.type = filter_type
        self.rubber_band = None
        self.feature_rubber_band = None
        self.iface = iface
        self.map_canvas = None
        self.settings = Settings()
        self.transform_ch = None
        self.transform_4326 = None
        self.map_tip = None
        self.current_timer = None
        self.crs = None
        self.event_loop = None
        self.result_found = False
        self.access_managers = {}
        self.nam_map_tip = None
        self.nam_fetch_feature = None

        if crs:
            self.crs = crs

        self.lang = get_language()

        self.searchable_layers = searchable_layers(self.lang, restrict=True)

        if iface is not None:
            # happens only in main thread
            self.map_canvas = iface.mapCanvas()
            self.map_canvas.destinationCrsChanged.connect(
                self.create_transforms)

            self.rubber_band = QgsRubberBand(self.map_canvas,
                                             QgsWkbTypes.PointGeometry)
            self.rubber_band.setColor(QColor(255, 255, 50, 200))
            self.rubber_band.setIcon(self.rubber_band.ICON_CIRCLE)
            self.rubber_band.setIconSize(15)
            self.rubber_band.setWidth(4)
            self.rubber_band.setBrushStyle(Qt.NoBrush)

            self.feature_rubber_band = QgsRubberBand(
                self.map_canvas, QgsWkbTypes.PolygonGeometry)
            self.feature_rubber_band.setColor(QColor(255, 50, 50, 200))
            self.feature_rubber_band.setFillColor(QColor(255, 255, 50, 160))
            self.feature_rubber_band.setBrushStyle(Qt.SolidPattern)
            self.feature_rubber_band.setLineStyle(Qt.SolidLine)
            self.feature_rubber_band.setWidth(4)

            self.create_transforms()
    def push_last_to_qgis(self, iface: QgisInterface) -> None:
        """
        Show last exception in QGIS log message window and as a message bar hint
        :param iface: QgisInterface representation
        :return: Nothing
        """
        split = self.last_exception.split('\n')
        if len(split) > 1:
            widget = iface.messageBar().createMessage("Error", self.last_exception.split('\n')[1])
        else:
            widget = iface.messageBar().createMessage("Error",
                                                      "An exception occurred during the process. " +
                                                      "For more details, please take a look to the log windows.")

        button = QPushButton(widget)
        button.setText("Show log windows")
        # noinspection PyUnresolvedReferences
        button.pressed.connect(self.iface.openMessageLog)
        widget.layout().addWidget(button)
        iface.messageBar().pushWidget(widget, level=2)

        # noinspection PyCallByClass, PyArgumentList
        QgsMessageLog.logMessage(self.last_exception, level=2)
Exemplo n.º 8
0
    def __init__(self,
                 data: dict,
                 iface: QgisInterface,
                 is_background: bool,
                 alternate_mode: bool = False):

        # debug
        for i, v in data.items():
            if i in ('qml', 'contacts'): continue
            if i == 'sublayers':
                for sublayer in data['sublayers']:
                    for j, u in sublayer.items():
                        if j in ('qml', 'contacts'): continue
                        dbg_info('*** sublayer {}: {}'.format(j, u))
            else:
                dbg_info('*** {}: {}'.format(i, v))

        data = self.reformat_data(data, is_background)

        settings = Settings()
        loading_mode: LoadingMode = settings.value(
            'default_layer_loading_mode')
        if alternate_mode:
            loading_mode = loading_mode.alternate_mode()

        if force_wms(data, is_background):
            loading_mode = LoadingMode.WMS

        # if background, insert at bottom of layer tree
        if is_background:
            root = QgsProject.instance().layerTreeRoot()
            pos = len(root.children())
            insertion_point = QgsLayerTreeRegistryBridge.InsertionPoint(
                root, pos)

        else:
            insertion_point = iface.layerTreeInsertionPoint()

        dbg_info("insertion point: {} {}".format(insertion_point.group.name(),
                                                 insertion_point.position))

        loading_options = LoadingOptions(
            wms_load_separate=settings.value('wms_load_separate'),
            wms_image_format=settings.value('wms_image_format'),
            loading_mode=loading_mode,
            pg_auth_id=settings.value('pg_auth_id'),
            pg_service=PG_SERVICE)

        data.load(insertion_point, loading_options)
def test_plugin_is_loaded_06(qgis_app: QgsApplication,
                             qgis_iface_menu: QgisInterface,
                             qgis_plugin: Dict[str, Any]):
    """
    Tests that the menu is located in the penultimate position of an existing menu

    :param qgis_app: QGIS application fixture
    :type qgis_app: QgsApplication
    :param qgis_iface_menu: QGIS interface fixture with an existing menu bar with menus A, B and C
    :type qgis_iface_menu: QgisInterface
    :param qgis_plugin: QGIS loading and unloading fixture for plugins
    :type qgis_plugin: dict of Any
    """
    actions: List[QAction] = qgis_iface_menu.mainWindow().menuBar().actions()
    assert actions[-2].text() == 'Gis&FIRE'
Exemplo n.º 10
0
def ensure_folder_empty(folder: str, iface: QgisInterface) -> bool:
    existing_files = os.listdir(folder)
    if not existing_files:
        return True
    reply = QMessageBox.question(
        iface.mainWindow(), 'Existing files',
        'The folder {} is not empty and its contents will be removed.'.format(
            folder), QMessageBox.Ok, QMessageBox.Cancel)
    if reply == QMessageBox.Cancel:
        return False
    for filename in existing_files:
        path = os.path.join(folder, filename)
        if os.path.isdir(path):
            shutil.rmtree(path)
        else:
            os.unlink(path)
    return True
    def __init__(self, service: Service, iface: QgisInterface = None):
        super().__init__()
        self.service = service.clone()
        self.rubberband = None
        self.iface = None
        self.map_canvas = None
        self.current_timer = None
        self.settings = Settings()
        self.crs = QgsCoordinateReferenceSystem(self.service.crs)

        # only get map_canvas on main thread, not when cloning
        if iface is not None:
            self.iface = iface
            self.map_canvas = iface.mapCanvas()

            self.rubberband = QgsRubberBand(self.map_canvas)
            self.reset_rubberband()
Exemplo n.º 12
0
    def __init__(self, iface: QgisInterface, parent=None):
        """Constructor."""
        super(QuickApiDialog, self).__init__(parent)
        self.setupUi(self)
        self.iface = iface

        # Instantiate a network access manager
        self.nominatim = Nominatim()
        self.point_tool = PointTool(iface.mapCanvas())
        self.last_map_tool: QgsMapTool = None

        # Set up widgets
        self.map_button.setIcon(
            QIcon(":images/themes/default/cursors/mCapturePoint.svg"))
        self.crs_input.setCrs(QgsCoordinateReferenceSystem("EPSG:4326"))

        # Set up callbacks
        self.finished.connect(self.request_geocoder)
        self.map_button.clicked.connect(self._on_map_click)
        self.point_tool.canvasClicked.connect(self._write_line_widget)
        self.point_tool.deactivated.connect(
            lambda: QApplication.restoreOverrideCursor())
    def __init__(self, iface: QgisInterface = None):
        super().__init__()
        self.rubber_band = None
        self.settings = Settings()
        self.iface = None
        self.map_canvas = None
        self.current_timer = None
        self.transform = None

        # only get map_canvas on main thread, not when cloning
        if iface is not None:
            self.iface = iface
            self.map_canvas = iface.mapCanvas()
            self.map_canvas.destinationCrsChanged.connect(
                self.create_transform)

            self.rubber_band = QgsRubberBand(self.map_canvas)
            self.rubber_band.setColor(QColor(255, 255, 50, 200))
            self.rubber_band.setIcon(self.rubber_band.ICON_CIRCLE)
            self.rubber_band.setIconSize(15)
            self.rubber_band.setWidth(4)
            self.rubber_band.setBrushStyle(Qt.NoBrush)

            self.create_transform()
Exemplo n.º 14
0
    def __init__(self, iface: QgisInterface, html: str, point: QgsPointXY):
        super().__init__()
        self.map_canvas = iface.mapCanvas()
        self.point = point
        self.web_view = QWebView(self)

        self.dbg_info('map position: {}'.format(point.asWkt()))

        self.web_view.page().setLinkDelegationPolicy(
            QWebPage.DelegateAllLinks)  # Handle link clicks by yourself
        self.web_view.setContextMenuPolicy(
            Qt.NoContextMenu
        )  # No context menu is allowed if you don't need it
        self.web_view.linkClicked.connect(self.on_link_clicked)

        self.web_view.page().settings().setAttribute(
            QWebSettings.DeveloperExtrasEnabled, True)
        self.web_view.page().settings().setAttribute(
            QWebSettings.JavascriptEnabled, True)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setWidget(self.web_view)

        # assure the map tip is never larger than half the map canvas
        max_width = int(self.map_canvas.geometry().width() / 1.8)
        max_height = int(self.map_canvas.geometry().height() / 1.8)
        self.dbg_info('max size {} {}'.format(max_height, max_width))
        self.setMaximumSize(max_width, max_height)

        # start with 0 size,
        # the content will automatically make it grow up to MaximumSize
        self.resize(300, 200)

        background_color = self.palette().base().color()
        background_color.setAlpha(235)
        stroke_color = self.palette().shadow().color()
        #self.setStyleSheet(".QDocWidget{{ border: 1px solid {stroke}; background-color: {bg} }}"
        #                          .format(stroke=stroke_color.name(QColor.HexArgb),
        #                                  bg=background_color.name(QColor.HexArgb)))

        palette = self.web_view.palette()
        palette.setBrush(QPalette.Base, Qt.transparent)
        palette.setBrush(QPalette.Base, background_color)
        self.web_view.page().setPalette(palette)
        self.web_view.setAttribute(Qt.WA_OpaquePaintEvent, False)

        body_style = "background-color: {bg}; margin: 0".format(
            bg=background_color)
        container_style = "display: inline-block; margin: 0px"

        body_html = "<html><body style='{body_style}'>" \
                    "<div id='QgsWebViewContainer' style='{container_style}'>{html}</div><" \
                    "/body></html>".format(body_style=body_style,
                                           container_style=container_style,
                                           html=html)

        self.web_view.setHtml(body_html)

        scrollbar_width = self.web_view.page().mainFrame().scrollBarGeometry(
            Qt.Vertical).width()
        scrollbar_height = self.web_view.page().mainFrame().scrollBarGeometry(
            Qt.Horizontal).height()
        if scrollbar_width > 0 or scrollbar_height > 0:
            # Get the content size
            container = self.web_view.page().mainFrame().findFirstElement(
                "#QgsWebViewContainer")
            width = container.geometry().width() + 25 + scrollbar_width
            height = container.geometry().height() + 25 + scrollbar_height

            #self.resize(width, height)

        iface.addDockWidget(Qt.RightDockWidgetArea, self)
        self.setFeatures(QDockWidget.AllDockWidgetFeatures)
        self.setFloating(True)
        self.setWindowOpacity(0.9)
        self.move_to_point()
Exemplo n.º 15
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFload_standard_layersACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from qgis.PyQt import QtGui, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from qgis.PyQt.QtCore import QCoreApplication, QSettings
        from qgis.gui import QgisInterface
    except ImportError:
        return None, None, None, None

    global QGIS_APP  # pylint: disable=W0603

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file instead
        # of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('IsochronesTesting')

        # noinspection PyPep8Naming
        QGIS_APP = QgsApplication(sys.argv, gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()

        # Save some settings
        settings = QSettings()
        settings.setValue('locale/overrideFlag', True)
        settings.setValue('locale/userLocale', 'en_US')
        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2

    global PARENT  # pylint: disable=W0603
    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    global IFACE  # pylint: disable=W0603
    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Exemplo n.º 16
0
 def __init__(self, iface: QgisInterface) -> None:
     self.msg_bar = iface.messageBar()  # type: QgsMessageBar