Example #1
0
 def addIconPath(self):
     print(u'addIconPath')
     iconsDir = os.path.join(self.dataPath, u'SIMS-Icons')
     paths = QgsApplication.svgPaths()
     if not iconsDir in paths:
         paths.append(iconsDir)
     QgsApplication.setDefaultSvgPaths(paths)
Example #2
0
 def removeIconPath(self):
     print(u'removeIconPath')
     iconsDir = os.path.join(self.dataPath, u'SIMS-Icons')
     paths = QgsApplication.svgPaths()
     i = paths.index(iconsDir)
     if i >= 0:
         del paths[i]
     QgsApplication.setDefaultSvgPaths(paths)
    def on_exception_but_clicked(self):
        # Local vars for testing value display in debugger
        t01 = QgsApplication.pluginPath()
        t02 = QgsApplication.svgPaths()
        # t03 = QChar('x')
        t04 = QPoint(4, 5)
        t05 = QPointF(4.1, 5.1)
        t06 = QDate()
        t07 = QTime()
        t08 = QDir()
        t09 = QFile()
        t10 = QUrl()

        x01 = 42
        x02 = "fortytwo"

        raise Exception("Exception raised. Check local variables in your debugger.")
Example #4
0
    def on_exception_but_clicked(self):
        #Local vars for testing value display in debugger
        t01 = QgsApplication.pluginPath()
        t02 = QgsApplication.svgPaths()
        #t03 = QChar('x')
        t04 = QPoint(4, 5)
        t05 = QPointF(4.1, 5.1)
        t06 = QDate()
        t07 = QTime()
        t08 = QDir()
        t09 = QFile()
        t10 = QUrl()

        x01 = 42
        x02 = 'fortytwo'

        raise Exception(
            "Exception raised. Check local variables in your debugger.")
 def prepareIconForUpload(self, svgIconName):
     svgPaths = QgsApplication.svgPaths()
     svgIconPath = None
     for dir in svgPaths:
         if os.path.isfile(os.path.join(dir, svgIconName)):
             svgIconPath = os.path.join(dir, svgIconName)
     if svgIconPath is None or not svgIconPath.endswith('svg'):
         return False
     name = os.path.splitext(svgIconName)[0]
     outputPath = os.path.join(self.icondir, 'qgis-' + name + '.png')
     img = QIcon(svgIconPath).pixmap(QSize(100, 100)).toImage()
     if img.save(outputPath):
         newId = self.uploadImage(outputPath)
         if newId:
             iconUrl = self.baseurl + 'projectimage/getThumbnail.action?id='
             iconUrl += str(newId)
             return iconUrl
     self.userInfo(400, 'Custom symbology icon', 'uploaded')
     return False
    def resolve_dependency(self, xml_path):
        """Modify the xml and resolve the resources dependency.

        We need to update any path dependency of downloaded symbol so that
        the path points to the right path after it's installed.

        For now, we only update the svg/image path to the svg/ directory of
        the collection if the svg exists.

        :param xml_path: The path to the style xml file.
        :type xml_path: str
        """
        with open(xml_path, 'r') as xml_file:
            symbol_xml = xml_file.read()

        updated_xml = fix_xml_node(symbol_xml, self.collection_path,
                                   QgsApplication.svgPaths())

        with open(xml_path, 'w') as xml_file:
            xml_file.write(updated_xml)
    def resolve_dependency(self, xml_path):
        """Modify the XML and resolve dependencies.

        Update paths to downloaded symbol so that the paths
        point to the right location.

        For now, we only update the svg/image paths to the
        svg directory of the collection if the SVG file exists
        there.

        :param xml_path: The path to the XML style file.
        :type xml_path: str
        """
        with open(xml_path, 'rb') as xml_file:
            symbol_xml = xml_file.read()

        updated_xml = fix_xml_node(symbol_xml, str(self.collection_path),
                                   QgsApplication.svgPaths())

        with open(xml_path, 'wb') as xml_file:
            xml_file.write(updated_xml)
# coding: utf-8
from PyQt4.QtCore import QSettings
from qgis.core import QgsApplication
from qgis.gui import QgsSvgSelectorWidget

# Print the SVG paths
print(QgsApplication.svgPaths())

# Specific to our use case.
# QgsApplication.setDefaultSvgPaths did not alter all the paths.
# Default value for "svg/searchPathsForSVG" is $HOME but as we had many git
# repositories under $HOME, QGIS was scanning all of them to look for SVG.
# Uncomment or not depending of your case
# s = QSettings()
# s.setValue("svg/searchPathsForSVG", "/tmp")  # Change the path if on Windows

# To confirm the difference if you apply above two previous lines
print(QgsApplication.svgPaths())

svg_selector_widget = QgsSvgSelectorWidget()
svg_selector_widget.show()


def on_svg_selected(path):
    print(path)


# Signal
svg_selector_widget.svgSelected.connect(on_svg_selected)

# Functions
 def _add_path_to_icons():
     icons_directory = get_icons_directory()
     current_paths = QgsApplication.svgPaths()
     if icons_directory not in current_paths:
         current_paths.append(icons_directory)
         QgsApplication.setDefaultSvgPaths(current_paths)
# coding: utf-8
from PyQt4.QtCore import QSettings
from qgis.core import QgsApplication
from qgis.gui import QgsSvgSelectorWidget

# Print the SVG paths
print(QgsApplication.svgPaths())

# Specific to our use case.
# QgsApplication.setDefaultSvgPaths did not alter all the paths.
# Default value for "svg/searchPathsForSVG" is $HOME but as we had many git
# repositories under $HOME, QGIS was scanning all of them to look for SVG.
# Uncomment or not depending of your case
# s = QSettings()
# s.setValue("svg/searchPathsForSVG", "/tmp")  # Change the path if on Windows

# To confirm the difference if you apply above two previous lines
print(QgsApplication.svgPaths())

svg_selector_widget = QgsSvgSelectorWidget()
svg_selector_widget.show()


def on_svg_selected(path):
    print(path)

# Signal
svg_selector_widget.svgSelected.connect(on_svg_selected)

# Functions
print(svg_selector_widget.currentSvgPath())  # Path in the current bottom left QLineEdit
Example #11
0
    def renderer(self):
        if 'QGIS_AUTH_DB_DIR_PATH' not in os.environ:
            os.environ['QGIS_AUTH_DB_DIR_PATH'] = '/tmp'

        qgis = None
        while True:
            options, result = self.queue.get()

            # Don't start QGIS until first request
            if qgis is None:
                qgis = QgsApplication([], False)
                qgis.setPrefixPath(self.settings.get('path'), True)
                qgis.setDefaultSvgPaths(qgis.svgPaths() +
                                        self.settings.get('svgpaths'))
                qgis.setMaxThreads(1)
                qgis.initQgis()

            try:
                if isinstance(options, LegendOptions):
                    style, = options

                    layer = self._qgs_memory_layer(style)
                    layer.setName(style.parent.display_name)

                    QgsMapLayerRegistry.instance().addMapLayer(layer)

                    root = QgsLayerTreeGroup()
                    root.addLayer(layer)

                    # 'Cannot create a QPixmap when no GUI is being used'
                    #  warning occurs here
                    model = QgsLayerTreeModel(root)

                    settings = QgsLegendSettings()
                    settings.setTitle('')
                    settings.setBoxSpace(1)
                    settings.setSymbolSize(QSizeF(5, 3))
                    settings.setDpi(96)

                    renderer = QgsLegendRenderer(model, settings)

                    # Dots per mm
                    dpmm = settings.dpi() / 25.4

                    min_size = renderer.minimumSize()
                    size = QSize(dpmm * min_size.width(),
                                 dpmm * min_size.height())
                    img = QImage(size, QImage.Format_ARGB32)
                    img.fill(QColor(0, 0, 0, 0))

                    painter = QPainter()
                    painter.begin(img)
                    painter.scale(dpmm, dpmm)
                    renderer.drawLegend(painter)
                    painter.end()

                    QgsMapLayerRegistry.instance().removeAllMapLayers()

                    ba = QByteArray()
                    bf = QBuffer(ba)
                    bf.open(QIODevice.WriteOnly)
                    img.save(bf, 'PNG')
                    bf.close()

                    buf = StringIO()
                    buf.write(bf.data())
                    buf.seek(0)
                    result.put(buf)

                else:
                    path = features = None
                    if isinstance(options, VectorRenderOptions):
                        style, features, render_size, \
                            extended, target_box = options
                        layer = self._qgs_memory_layer(style,
                                                       features=features)
                    elif isinstance(options, RasterRenderOptions):
                        style, path, render_size, \
                            extended, target_box = options
                        layer = QgsRasterLayer(path)
                        layer.loadNamedStyle(
                            self.env.file_storage.filename(style.qml_fileobj))

                    settings = QgsMapSettings()
                    settings.setLayers([layer.id()])
                    settings.setFlag(QgsMapSettings.DrawLabeling)
                    settings.setFlag(QgsMapSettings.Antialiasing)

                    settings.setCrsTransformEnabled(True)
                    settings.setDestinationCrs(layer.crs())
                    settings.setMapUnits(layer.crs().mapUnits())
                    settings.setOutputSize(QSize(*render_size))
                    settings.setExtent(QgsRectangle(*extended))

                    settings.setOutputImageFormat(QImage.Format_ARGB32)
                    bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0))
                    settings.setBackgroundColor(bgcolor)
                    settings.setOutputDpi(96)

                    QgsMapLayerRegistry.instance().addMapLayer(layer)
                    settings.setLayers([layer.id()])

                    # Create QImage by hand to be able to use
                    # QgsMapRendererCustomPainterJob. Others will not
                    # allow to workaround a bug with overlay rendering.
                    img = QImage(settings.outputSize(), QImage.Format_ARGB32)

                    # These cludges are needed for rendering
                    # on transparent background, otherwise it's a mess.
                    img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255)))
                    img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0)))

                    # DPI should be equal to settings, otherwise an error.
                    # In QImage the resolution is set in dots per meter
                    # for each axis.
                    dpm = settings.outputDpi() / 25.4 * 1000
                    img.setDotsPerMeterX(dpm)
                    img.setDotsPerMeterY(dpm)

                    painter = QPainter(img)
                    job = QgsMapRendererCustomPainterJob(settings, painter)
                    job.renderSynchronously()
                    painter.end()

                    QgsMapLayerRegistry.instance().removeAllMapLayers()

                    img = self._qimage_to_pil(img)

                    # Clip needed part
                    result.put(img.crop(target_box))

                    # Cleanup
                    if path is not None:
                        gdal.Unlink(path)

            except Exception as exc:
                self.logger.error(exc.message)
                result.put(exc)

        qgis.exitQgis()
Example #12
0
 def check_styles_paths(self):
     plugin_svg_path = path.join(self.plugin_dir, 'svg/')
     svg_paths = QgsApplication.svgPaths()
     if not plugin_svg_path in svg_paths:
         svg_paths.append(plugin_svg_path)
         QgsApplication.setDefaultSvgPaths(svg_paths)
Example #13
-1
def getQgisTestApp():
    """ Start one QGis application to test agaist

    Input
        NIL

    Output
        handle to qgis app


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

    global QGISAPP  # pylint: disable=W0603

    if QGISAPP is None:
        myGuiFlag = True  # All test will run qgis in gui mode
        QGISAPP = QgsApplication(sys.argv, myGuiFlag)
        if 'QGIS_PREFIX_PATH' in os.environ:
            myPath = os.environ['QGIS_PREFIX_PATH']
            myUseDefaultPathFlag = True
            QGISAPP.setPrefixPath(myPath, myUseDefaultPathFlag)

        if sys.platform.startswith('darwin'):
            # override resource paths, otherwise looks for Resources in app
            if 'QGIS_MAC_PKGDATA_DIR' in os.environ:
                myPkgPath = os.environ['QGIS_MAC_PKGDATA_DIR']
                QGISAPP.setPkgDataPath(myPkgPath)
            if 'QGIS_MAC_SVG_DIR'  in os.environ:
                mySVGPath = os.environ['QGIS_MAC_SVG_DIR']
                mySVGPaths = QGISAPP.svgPaths()
                # doesn't get rid of incorrect path, just adds correct one
                mySVGPaths.prepend(mySVGPath)
                QGISAPP.setDefaultSvgPaths(mySVGPaths)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        print s

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

    global CANVAS  # pylint: disable=W0603
    if CANVAS is None:
        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
        IFACE = QgisInterface(CANVAS)

    return QGISAPP, CANVAS, IFACE, PARENT