2

I have a complement (image_1) that works perfect. But I get an error by wanting to make a change.

enter image description here

I add the code of my two .py files.

I want to change this address: "C:/Users/SENARA/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/RiegoSenara/LogoSenara.png"

and use this:

 os.path.join(os.path.dirname(__file__),"LogoSenara.png")

This works in the complemento.py

 DialogBase, DialogType = uic.loadUiType(os.path.join(os.path.dirname(__file__), 
                                                      u'DialogoEjemplo1.ui'))

But it doesn't work in qgis_minimal_plugin.py

 self.action = QAction(QIcon(os.path.join(os.path.dirname(__file__), u"LogoSenara.png"), 
                             QCoreApplication.translate('RiegoSenara', 'RiegoSenara'),
                             self.iface.mainWindow())

Image_2

enter image description here

This gives me the following error: NameError: name __file__ is not defined. Other times it doesn't work at all.

Image_3

enter image description here

FOLDER CODE COMPLEMENTO

 from PyQt5 import uic
 from PyQt5.QtGui import *
 import os
 from qgis.core import QgsVectorLayer
 from qgis.core import *
 from qgis.utils import *
 from PyQt5.QtWidgets import *
 from pathlib import Path, PureWindowsPath

 #DialogBase, DialogType = 
 uic.loadUiType(os.path.join(os.path.dirname(__file__), 
 u'DialogoEjemplo1.ui'), resource_suffix='')
 DialogBase, DialogType =   
 uic.loadUiType(os.path.join(os.path.dirname(__file__),
 u'DialogoEjemplo1.ui'))

 class GeometryOperationDialog(DialogType, DialogBase):

def __init__(self,parent=None):
    super().__init__(parent)
    self.setupUi(self)

    self.Buscar.clicked.connect(self.loadLayers)
    self.Buscar1.clicked.connect(self.cargarnodos)

 #        self.loadLayers()
 #        self.cargarnodos()

def loadLayers(self):
    #Cargando el archivo con rutas de hojas cartográficas y archivos de texto del proyecto
    global Nuevaruta
    global Rutanueva
    self.file_path = QFileDialog.getOpenFileName(self, 'Cargar Lineas', './', filter="All Files(*.*);;Text Files(*.txt)")

    if self.file_path[0]:
       self.file_name = (self.file_path[0].split('/'))[-1]
       Narchivo=len(self.file_name)
       self.setWindowTitle("{} - Notepad".format(self.file_name))

       file_open = open(self.file_path[0], 'r+')
       Nuevaruta = Path(self.file_path[0])
       Cadena1=len(str(Nuevaruta))
       Nuevaruta2=str(Nuevaruta)
       fincadena=int(Cadena1-Narchivo-1)
       Rutanueva=Nuevaruta2 [0:fincadena]

#        Cargando un archivo txt wkt(000 000, 000 000),separado por tabulaciones con datos de lineas
    fn4=str(Nuevaruta)+str("?encoding=UTF-8&delimiter=\\t&wktField=wkt_geom&useheader=no&crs=epsg:5367&decimal=.")
    layer1 = QgsVectorLayer("file:///"+fn4,"Conduccion","delimitedtext")
    # Compruebe si la capa es válida 
    if not layer1 . isValid ():
        print ( "Capa TXT NO cargada" )
    fn5=Rutanueva
    fn5=fn5.rstrip()
    fn5=fn5+"\Tuberiasdr.shp"
    fn5=fn5.rstrip()
    QgsVectorFileWriter.writeAsVectorFormat(layer1, fn5, 'UTF-8', layer1.crs(), 'ESRI Shapefile')
    #Conviertiendo archivo lineas temporal en Shape para diametros
    fn9=Rutanueva
    fn9=fn9.rstrip()
    fn9=fn9+"\Tuberiadiam.shp"
    fn9=fn9.rstrip()
    QgsVectorFileWriter.writeAsVectorFormat(layer1, fn9, 'UTF-8', layer1.crs(), 'ESRI Shapefile')

        #Cargando Shape Lineas sdr
    fn6=Rutanueva
    fn6=fn6.rstrip()
    fn6=fn6+"\Tuberiasdr.shp"
    fn6=fn6.rstrip()
    layer4 = QgsVectorLayer(fn6, 'TuberiaSDR', 'ogr')
    QgsProject.instance().addMapLayer(layer4)#Lo añado al mapa de capas
    #Cargando Shape Lineas diametro
    fn10=Rutanueva
    fn10=fn10.rstrip()
    fn10=fn10+"\Tuberiadiam.shp"
    fn10=fn10.rstrip()
    layer7 = QgsVectorLayer(fn10, 'TuberiaDiam', 'ogr')
    QgsProject.instance().addMapLayer(layer7)#Lo añado al mapa de capas
    QgsProject.instance().layerTreeRoot().findLayer(layer7.id()).setItemVisibilityChecked(False)#Quita el check de la capa para que no se muestre
    QgsProject.instance().layerTreeRoot().findLayer(layer7.id()).setExpanded(False)

#CATEGORIZADO SDR
    #Esta funcion detecta el tipo de geometria
    def validatedDefaultSymbol(geometryType):
        symbol = QgsSymbol.defaultSymbol(geometryType)
        if symbol is None:
            if geometryType == Qgis.Point:#== operador booleano true o false
                symbol = QgsMarkerSymbol()
            elif geometryType == Qgis.Line:
                symbol = QgsLineSymbol()
            elif geometryType == Qgis.Polygon:
                symbol = QgsFillSymbol()
        return symbol

    def makeSymbologyForRange(layer, min, max, title, color):#Funcion asigna color y ancho
        symbol = validatedDefaultSymbol(layer4.geometryType())
        symbol.setColor(color)
        symbol.setWidth(0.5)
        range = QgsRendererRange(min, max, symbol, title)#asigna min max tipo geometria y texto de titulo
        return range

    def applySymbologyFixedDivisions(layer, field):#Funcion crea rango categorizado
        rangeList = []#Crea un rango
        rangeList.append( makeSymbologyForRange(layer4, 14, 14, 'DR14', #Asigna valores a la lista del rango
    QColor("Green") ) )
        rangeList.append( makeSymbologyForRange(layer4, 17, 17, 'SDR17', #Asigna valores a la lista del rango
    QColor("Red") ) )
        rangeList.append( makeSymbologyForRange(layer4, 26, 26, 'SDR26',  
    QColor("Blue") ) )
        rangeList.append( makeSymbologyForRange(layer4, 32.5, 32.5, 'SDR32.5',  
    QColor("Yellow") ) )
        rangeList.append( makeSymbologyForRange(layer4, 41, 41, 'SDR41',  
    QColor("Black") ) )
        renderer = QgsGraduatedSymbolRenderer(field, rangeList)#Asigna parametros y titulo de columna con los valores
        renderer.setMode(QgsGraduatedSymbolRenderer.Custom)#setmode Obsoleto QGIS 3.10 use classficationMethod en su lugar
        layer4.setRenderer(renderer)

    if layer4.isValid():
        applySymbologyFixedDivisions(layer4, "SDR")
        QgsProject.instance().addMapLayer(layer4)

        #CATEGORIZADO DIAMETRO
    #Esta funcion detecta el tipo de geometria
    def validatedDefaultSymbol(geometryType):
        symbol = QgsSymbol.defaultSymbol(geometryType)
        if symbol is None:
            if geometryType == Qgis.Point:#== operador booleano true o false
                symbol = QgsMarkerSymbol()
            elif geometryType == Qgis.Line:
                symbol = QgsLineSymbol()
            elif geometryType == Qgis.Polygon:
                symbol = QgsFillSymbol()
        return symbol

    def makeSymbologyForRange(layer, min, max, title, color):#Funcion asigna color y ancho
        symbol = validatedDefaultSymbol(layer7.geometryType())
        symbol.setColor(color)
        symbol.setWidth(0.5)
        range = QgsRendererRange(min, max, symbol, title)#asigna min max tipo geometria y texto de titulo
        return range

    def applySymbologyFixedDivisions(layer, field):#Funcion crea rango categorizado
        rangeList = []#Crea un rango
        rangeList.append( makeSymbologyForRange(layer7, 0, 57, '2"', #Asigna valores a la lista del rango
    QColor("Black") ) )
        rangeList.append( makeSymbologyForRange(layer7, 57, 70, '2.5"', #Asigna valores a la lista del rango
    QColor("darkMagenta") ) )
        rangeList.append( makeSymbologyForRange(layer7, 70, 85, '3"',  
    QColor("Yellow") ) )
        rangeList.append( makeSymbologyForRange(layer7, 85, 109, '4"',  
    QColor("Green") ) )
        rangeList.append( makeSymbologyForRange(layer7, 109, 160, '6"',  
    QColor("Blue") ) )
        rangeList.append( makeSymbologyForRange(layer7, 160, 208, '8"',  
    QColor("Red") ) )
        rangeList.append( makeSymbologyForRange(layer7, 208, 260, '10"',  
    QColor("Cyan") ) )
        rangeList.append( makeSymbologyForRange(layer7, 260, 308, '12"',  
    QColor("Magenta") ) )
        renderer = QgsGraduatedSymbolRenderer(field, rangeList)#Asigna parametros y titulo de columna con los valores
        renderer.setMode(QgsGraduatedSymbolRenderer.Custom)#setmode Obsoleto QGIS 3.10 use classficationMethod en su lugar
        layer7.setRenderer(renderer)

    if layer7.isValid():
        applySymbologyFixedDivisions(layer7, "diametro")
        QgsProject.instance().addMapLayer(layer7)

        #Agregando Etiquetas a la Tubería diametro
        for layer in QgsProject.instance().mapLayers().values():
            layer_settings  = QgsPalLayerSettings()
            text_format = QgsTextFormat()

        text_format.setFont(QFont("Arial", 8))
        text_format.setSize(8)
        text_format.setColor(QColor('Black'))

        buffer_settings = QgsTextBufferSettings()
        buffer_settings.setEnabled(True)
        buffer_settings.setSize(0.10)
        buffer_settings.setColor(QColor('black'))

        text_format.setBuffer(buffer_settings)
        layer_settings.setFormat(text_format)

        layer_settings.fieldName = "diametro"
        layer_settings.placement = layer_settings.Line

        layer_settings.enabled = True

        layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
        layer4.setLabelsEnabled(True)
        layer4.setLabeling(layer_settings)
        layer4.triggerRepaint()

    #Agregando Etiquetas a la Tubería SDR
        for layer in QgsProject.instance().mapLayers().values():
            layer_settings  = QgsPalLayerSettings()
            text_format = QgsTextFormat()

        text_format.setFont(QFont("Arial", 8))
        text_format.setSize(8)
        text_format.setColor(QColor('Black'))

        buffer_settings = QgsTextBufferSettings()
        buffer_settings.setEnabled(True)
        buffer_settings.setSize(0.10)
        buffer_settings.setColor(QColor('black'))

        text_format.setBuffer(buffer_settings)
        layer_settings.setFormat(text_format)

        layer_settings.fieldName = "SDR"
        layer_settings.placement = layer_settings.Line

        layer_settings.enabled = True

        layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
        layer7.setLabelsEnabled(True)
        layer7.setLabeling(layer_settings)
        layer7.triggerRepaint()

def cargarnodos(self):
    self.file_path = QFileDialog.getOpenFileName(self, 'Cargar Nodos', './', filter="All Files(*.*);;Text Files(*.txt)")

    if self.file_path[0]:
       self.file_name = (self.file_path[1].split('/'))[-1]

       self.setWindowTitle("{} - Notepad".format(self.file_name))

       file_open = open(self.file_path[0], 'r+')
       Nuevaruta1 = Path(self.file_path[0])

    #Cargando un archivo txt de Puntos
    fn4=str(Nuevaruta1)+str("?encoding=UTF-8&delimiter=\\t&xField=COORDEX&yField=COORDEY&useheader=no&crs=epsg:5367&decimal=.")
    layer5 = QgsVectorLayer("file:///"+fn4,"Nodos","delimitedtext")
    # Compruebe si la capa es válida 
    if not layer5 . isValid ():
        print ( "Capa Nodos NO cargada" )
    #QgsProject.instance().addMapLayer(layer5)#Lo añado al mapa de capas
    #Conviertiendo archivo puntos temporal en Shape
    fn7=Rutanueva
    fn7=fn7.rstrip()
    fn7=fn7+"\Datos Puntos Qgis.shp"
    fn7=fn7.rstrip()
    QgsVectorFileWriter.writeAsVectorFormat(layer5, fn7, 'UTF-8', layer5.crs(), 'ESRI Shapefile')

    #Cargando Shape Puntos
    fn8=Rutanueva
    fn8=fn8.rstrip()
    fn8=fn8+"\Datos Puntos Qgis.shp"
    fn8=fn8.rstrip()
    layer6 = QgsVectorLayer(fn8, 'ObrasCiviles', 'ogr')
    QgsProject.instance().addMapLayer(layer6)#Lo añado al mapa de capas
    QgsProject.instance().layerTreeRoot().findLayer(layer6.id()).setExpanded(False)
    #Cargando Shape Puntos 2
    fn11=Rutanueva
    fn11=fn11.rstrip()
    fn11=fn11+"\Datos Puntos Qgis.shp"
    fn11=fn11.rstrip()
    layer11 = QgsVectorLayer(fn11, 'Nodos', 'ogr')
    QgsProject.instance().addMapLayer(layer11)#Lo añado al mapa de capas
    QgsProject.instance().layerTreeRoot().findLayer(layer11.id()).setItemVisibilityChecked(False)#Quita el check de la capa para que no se muestre
    # Definiendo la clase forma
    shape = QgsSimpleMarkerSymbolLayerBase

        # Creando un diccionario prara guardad campo,color, texto y forma
    land_class = {
        'PT': (QColor("blue"), 'PuenteTubo', shape. Arrow,3.5),
        'D': (QColor("yellow"), 'Desarenador', shape.Star,4),
        'TQ': (QColor("green"), 'TQuiebragradiente', shape.Diamond,3),
        'FT': (QColor("red"), 'Filtrado', shape.HalfSquare,3.5),
        'VT': (QColor("red"), 'Toma', shape.CrossFill,3),
        'R': (QColor("cyan"), 'Reservorio', shape.Pentagon,3.5),
    }
    # Crear una lista para almacenar propiedades de la simbologia
    categories = []
    # Iterate through the dictionary
    for classes, (colour, label, shape,tamaño) in land_class.items():
        # Define symbol based on layer's geometry
        symbol = QgsSymbol.defaultSymbol(layer6.geometryType())
        # Set shape
        symbol.symbolLayer(0).setShape(shape)
        # Set Size
        symbol.setSize(tamaño)
        # Set colour
        symbol.setColor(QColor(colour))

        # Set the renderer properties    
        category = QgsRendererCategory(classes, symbol, label, shape)
        categories.append(category)
    # Field name
    expression = 'VALVULA'
    # Set the categorized renderer
    renderer = QgsCategorizedSymbolRenderer(expression, categories)
    layer6.setRenderer(renderer)
    # Refresh layer
    layer6.triggerRepaint()
    QgsProject.instance().addMapLayer(layer6)

    #Agregando Etiquetas a los Puntos
    for layer in QgsProject.instance().mapLayers().values():
        layer_settings  = QgsPalLayerSettings()
        text_format = QgsTextFormat()

    text_format.setFont(QFont("Arial", 10))
    text_format.setSize(10)
    text_format.setColor(QColor('Red'))

    buffer_settings = QgsTextBufferSettings()
    buffer_settings.setEnabled(True)
    buffer_settings.setSize(0.05)
    buffer_settings.setColor(QColor('Red'))

    text_format.setBuffer(buffer_settings)
    layer_settings.setFormat(text_format)

    layer_settings.fieldName = """concat("PUNTO")"""
    layer_settings.isExpression=True#Agregado nuevo
    layer_settings.placement = 4

    layer_settings.enabled = True

    layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
    layer6.setLabelsEnabled(True)
    layer6.setLabeling(layer_settings)
    layer6.triggerRepaint()

    #Agregando Etiquetas a los Puntos Generales
    for layer in QgsProject.instance().mapLayers().values():
        layer_settings  = QgsPalLayerSettings()
        text_format = QgsTextFormat()

    text_format.setFont(QFont("Arial", 10))
    text_format.setSize(10)
    text_format.setColor(QColor('Red'))

    buffer_settings = QgsTextBufferSettings()
    buffer_settings.setEnabled(True)
    buffer_settings.setSize(0.05)
    buffer_settings.setColor(QColor('Red'))

    text_format.setBuffer(buffer_settings)
    layer_settings.setFormat(text_format)

    layer_settings.fieldName = """concat("PUNTO", ' (', "VALVULA",')')"""
    layer_settings.isExpression=True#Agregado nuevo
    layer_settings.placement = 4

    layer_settings.enabled = True

    layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
    layer11.setLabelsEnabled(True)
    layer11.setLabeling(layer_settings)
    layer11.triggerRepaint()

FOLDER CODE qgis_minimal_plugin

 import os
 from PyQt5.QtGui import *
 from PyQt5.QtWidgets import *
 from PyQt5.QtCore import *
 from .Complemento import GeometryOperationDialog
 #from .MapaQgis import Mapa
 #from .Prueba import Mensaje

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

 def initGui(self):
    self.action = 



 QAction(QIcon("C:/Users/SENARA/AppData/Roaming/QGIS/QGIS3/profiles/
 default/python/plugins/RiegoSenara/LogoSenara.png"),
                      QCoreApplication.translate('RiegoSenara', 
 'RiegoSenara'),
                      self.iface.mainWindow())
 #        print (os.path.join(os.path.dirname(__file__),"LogoSenara.png"))
 #        self.action = 
 QAction(QIcon(os.path.join(os.path.dirname(__file__),u"LogoSenara.png"),
 #                          QCoreApplication.translate('RiegoSenara', 
 'RiegoSenara'),
 #                          self.iface.mainWindow())

 #        self.action = 
 QAction(QIcon(os.path.join(os.path.dirname(__file__), "LogoSenara.png")),
 #                           self.tr('RiegoSenara'),
 #                           self.iface.mainWindow())
 #        self.action = QAction(u'RiegoSenara', self.iface.mainWindow())
    self.action.triggered.connect(self.run)
    self.iface.addToolBarIcon(self.action)

 #    def AbrirArchivo(self):
 #        filename=QFileDialog.getSaveFileName(self,"Selecione Hoja(s) 
 Cartograficas","",'*.txt')
 #        self.dlg.lineEdit.setText(filename)

def unload(self):
    self.iface.removeToolBarIcon(self.action)
    del self.action

    def run(self):
   #        QMessageBox.information(None, u'Minimal plugin',u'Do something 
   useful here')
    dialogo=GeometryOperationDialog()
    dialogo.exec_()                                                                                                                                 
 #        mens=Mensaje()
 #        MiClase=Mapa()
 #        MiClase.exec_()

FOLDER CODE __init__

 from .qgis_minimal_plugin import MinimalPlugin


 def classFactory(iface):
 return MinimalPlugin(iface)
1

This is what I was looking for. I found it in the WKT plugin code

 current_directory = 
 os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
 self.action = QAction(QIcon(os.path.join(current_directory, "icons", 
 "LogoSenara.png")),"&RiegoSenara", self.iface.mainWindow())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.