Ejemplo n.º 1
0
 def drawDataTable(
         self,
         tab):  # Called when user switches tabWidget to the Table Preview
     if tab != 1 or self.needsRedraw == False: return
     fields = self.fields
     self.dataTable.clear()
     self.repaint()
     self.dataTable.setColumnCount(len(fields))
     self.dataTable.setRowCount(self.provider.featureCount())
     header = []
     for i in fields.values():
         header.append(i.name())
     self.dataTable.setHorizontalHeaderLabels(header)
     self.progressBar.setRange(0, len(self.data) + 1)
     self.progressBar.setFormat(self.tr('Drawing table') + ': %p%')
     formatting = True
     if formatting:  # slower procedure, with formatting the table items
         for i in range(len(self.data)):
             self.progressBar.setValue(i + 1)
             for j in range(len(self.data[i])):
                 item = QTableWidgetItem(unicode(self.data[i][j] or 'NULL'))
                 item.setFlags(Qt.ItemIsSelectable)
                 if fields[i].type() == 6 or fields[i].type() == 2:
                     item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
                 self.dataTable.setItem(j, i, item)
     else:  # about 25% faster procedure, without formatting
         for i in range(len(self.data)):
             self.progressBar.setValue(i + 1)
             for j in range(len(self.data[i])):
                 self.dataTable.setItem(
                     j, i,
                     QTableWidgetItem(unicode(self.data[i][j] or 'NULL')))
     self.dataTable.resizeColumnsToContents()
     self.needsRedraw = False
     self.progressBar.reset()
Ejemplo n.º 2
0
 def carregaTabMats(self, tbMats):
     tableWidget = self.dlg.findChild(QTableWidget, 'tableWidget')
     tableWidget.setRowCount(0)
     tableWidget.setColumnCount(0)
     for i, tbMat in enumerate(tbMats):
         row = tableWidget.rowCount()
         tableWidget.insertRow(row)
         tableWidget.setColumnCount(len(tbMat))
         if row < 1:
             tableWidget.setHorizontalHeaderLabels(tbMat)
         else:
             for column, data in enumerate(tbMat):
                 if column == 0:
                     cell_widget = QWidget()
                     lay_out = QHBoxLayout(cell_widget)
                     chk_bx = QCheckBox()
                     if data in [1, '1', 't', 'True']:
                         chk_bx.setCheckState(QtCore.Qt.Checked)
                     else:
                         chk_bx.setCheckState(QtCore.Qt.Unchecked)
                     lay_out.addWidget(chk_bx)
                     lay_out.setAlignment(Qt.AlignCenter)
                     lay_out.setContentsMargins(0, 0, 0, 0)
                     cell_widget.setLayout(lay_out)
                     tableWidget.setCellWidget(row, 0, cell_widget)
                 else:
                     item = QTableWidgetItem("{}".format(data))  #:7.2f
                     item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                     tableWidget.setItem(row, column, item)
     #tableWidget.setHorizontalHeaderLabels(['On','DN','Diameter','Roughness','Pressure','Headloss','Reference'])
     #for i in range(1,4):
     #    tableWidget.resizeColumnToContents(i)
     tableWidget.removeRow(0)
     tableWidget.resizeColumnsToContents()
Ejemplo n.º 3
0
    def _getTextCell(self,
                     text: str,
                     enabled: bool = False) -> QTableWidgetItem:
        widget = QTableWidgetItem(text)
        widget.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        if not enabled:
            widget.setFlags(Qt.ItemIsEditable)

        return widget
Ejemplo n.º 4
0
def create_label(text):
    """
    Create a simple label item
    :param text: String - The text to insert inside the cell
    :return: QTableWidgetItem - The item to insert
    """
    item = QTableWidgetItem(text)
    item.setFlags(Qt.NoItemFlags)
    item.setTextAlignment(Qt.AlignCenter)
    return item
Ejemplo n.º 5
0
    def create_table(self):
        from AcATaMa.gui.acatama_dockwidget import AcATaMaDockWidget as AcATaMa

        header = ["Pix Val", "Color", "Select"]
        # get color table from raster
        thematic_table = {"color_table": get_color_table(
            AcATaMa.dockwidget.QCBox_ThematicRaster.currentLayer(),
            band=int(AcATaMa.dockwidget.QCBox_band_ThematicRaster.currentText()),
            nodata=int(AcATaMa.dockwidget.nodata_ThematicRaster.value()))}

        if not thematic_table["color_table"]:
            # clear table
            self.tableOfClasses.setRowCount(0)
            self.tableOfClasses.setColumnCount(0)
            return
        thematic_table["row_count"] = len(list(thematic_table["color_table"].values())[0])
        # init table
        self.tableOfClasses.setRowCount(thematic_table["row_count"])
        self.tableOfClasses.setColumnCount(3)
        # hidden row labels
        self.tableOfClasses.verticalHeader().setVisible(False)
        # add Header
        self.tableOfClasses.setHorizontalHeaderLabels(header)

        # insert items
        for n, h in enumerate(header):
            if h == "Pix Val":
                for m, item in enumerate(thematic_table["color_table"]["Pixel Value"]):
                    item_table = QTableWidgetItem(str(item))
                    item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    item_table.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
                    self.tableOfClasses.setItem(m, n, item_table)
            if h == "Color":
                for m in range(thematic_table["row_count"]):
                    item_table = QTableWidgetItem()
                    item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    item_table.setBackground(QColor(thematic_table["color_table"]["Red"][m],
                                                    thematic_table["color_table"]["Green"][m],
                                                    thematic_table["color_table"]["Blue"][m],
                                                    thematic_table["color_table"]["Alpha"][m]))
                    self.tableOfClasses.setItem(m, n, item_table)
            if h == "Select":
                for m in range(thematic_table["row_count"]):
                    item_table = QPushButton("Select this")
                    item_table.clicked.connect(self.select_clicked)
                    self.tableOfClasses.setCellWidget(m, n, item_table)

        # adjust size of Table
        self.tableOfClasses.resizeColumnsToContents()
        self.tableOfClasses.resizeRowsToContents()
        # adjust the dialog based on table content
        dialog_width = self.tableOfClasses.horizontalHeader().length() + 50
        self.resize(dialog_width, self.height())
Ejemplo n.º 6
0
 def ImportaTubos(self):
     #MsgTxt=self.tr(u'Importa tubos!')
     #QMessageBox.information(None,self.SETTINGS,MsgTxt)
     self.table = self.ui.tableWidget
     prjfi = os.path.splitext(QgsProject.instance().fileName())[0] + '.csv'
     path, __ = QFileDialog.getOpenFileName(self, 'Open File', prjfi,
                                            'CSV(*.csv)')
     if path:
         if os.path.exists(path):
             with open(str(path), 'r', newline='') as stream:
                 self.table.setRowCount(0)
                 self.table.setColumnCount(0)
                 for rowdata in csv.reader(stream):
                     self.table.setColumnCount(len(rowdata))
                     row = self.table.rowCount()
                     self.table.insertRow(row)
                     if row < 1:
                         self.table.setHorizontalHeaderLabels(rowdata)
                     else:
                         for column, data in enumerate(rowdata):
                             valor = data  #.decode('utf8')
                             if column == 0:
                                 cell_widget = QWidget()
                                 lay_out = QHBoxLayout(cell_widget)
                                 chk_bx = QCheckBox()
                                 if valor in [1, '1', 't', 'True']:
                                     chk_bx.setCheckState(QtCore.Qt.Checked)
                                 else:
                                     chk_bx.setCheckState(
                                         QtCore.Qt.Unchecked)
                                 lay_out.addWidget(chk_bx)
                                 lay_out.setAlignment(Qt.AlignCenter)
                                 lay_out.setContentsMargins(0, 0, 0, 0)
                                 cell_widget.setLayout(lay_out)
                                 self.table.setCellWidget(
                                     row, 0, cell_widget)
                             else:
                                 item = QTableWidgetItem(
                                     data)  #.decode('utf8')
                                 item.setTextAlignment(Qt.AlignVCenter
                                                       | Qt.AlignRight)
                                 self.table.setItem(row, column, item)
                 #self.table.setHorizontalHeaderLabels(['On','DN','Diameter','Roughness','Pressure','Referencia'])
                 #for i in range(1,4):
                 #    self.table.resizeColumnToContents(i)
                 self.table.removeRow(
                     0
                 )  #Remove a primeira linha em branco auxiliar para inserir o cabecalho
                 self.table.resizeColumnsToContents(
                 )  #Para ajustar todas as colunas de vez
Ejemplo n.º 7
0
    def btnFlow_push(self):
        frm = self.ui
        tableWidget = frm.tableWidget
        cabecalho = self.LeCabecalho(tableWidget)

        #CheckFields
        campos = ['Diameter', 'Roughness', 'Headloss']
        missingFields = []
        for campo in campos:
            if not campo in cabecalho:
                missingFields.append(campo)
        if missingFields:
            self.iface.messageBar().pushMessage(self.SETTINGS,
                                                'Missing fields: [' +
                                                ''.join(missingFields) + ']',
                                                level=Qgis.Warning,
                                                duration=3)
            return False

        #Check Max Flow field
        nroCols = tableWidget.columnCount()
        maxFlowFld = 'Max Flow'
        if maxFlowFld not in cabecalho:
            tableWidget.insertColumn(nroCols)
            cabecalho.append(maxFlowFld)
            tableWidget.setHorizontalHeaderLabels(cabecalho)

        #get Columns Index
        diamIdx = cabecalho.index(campos[0])
        roughIdx = cabecalho.index(campos[1])
        headIdx = cabecalho.index(campos[2])
        maxFlowIdx = cabecalho.index(maxFlowFld)

        #import GhyEconomicDiameter class to get colebrook function
        from .ghyeconomicdiameter import GhyEconomicDiameter as ghyDiam

        #iterate throught table widget rows
        for row in range(tableWidget.rowCount()):
            d = float(eval(tableWidget.item(row, diamIdx).text()))
            e = float(eval(tableWidget.item(row, roughIdx).text()))
            j = float(eval(tableWidget.item(row, headIdx).text()))
            # arguments 'Flow','Diameter' not used, it is only for instance creation
            vazao = ghyDiam('Flow', 'Diameter').ColebrookVazao(j, d, e)

            item = QTableWidgetItem('{0:.3f}'.format(vazao))  #.decode('utf8')
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            tableWidget.setItem(row, maxFlowIdx, item)
Ejemplo n.º 8
0
    def populate_function_table_1(self):
        """Populate the tblFunctions1 table with available functions."""
        hazards = deepcopy(hazard_all)
        exposures = exposure_all

        self.lblAvailableFunctions1.clear()
        self.tblFunctions1.clear()
        self.tblFunctions1.setColumnCount(len(hazards))
        self.tblFunctions1.setRowCount(len(exposures))
        for i in range(len(hazards)):
            hazard = hazards[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(hazard)))
            item.setText(hazard['name'].capitalize())
            item.setTextAlignment(Qt.AlignLeft)
            self.tblFunctions1.setHorizontalHeaderItem(i, item)
        for i in range(len(exposures)):
            exposure = exposures[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(exposure)))
            item.setText(exposure['name'].capitalize())
            self.tblFunctions1.setVerticalHeaderItem(i, item)
        developer_mode = setting('developer_mode', False, bool)
        for hazard in hazards:
            for exposure in exposures:
                item = QTableWidgetItem()
                if (exposure in hazard['disabled_exposures'] and not
                        developer_mode):
                    background_colour = unavailable_option_color
                    # Set it disable and un-selectable
                    item.setFlags(
                        item.flags() & ~
                        Qt.ItemIsEnabled & ~
                        Qt.ItemIsSelectable
                    )
                else:
                    background_colour = available_option_color
                item.setBackground(QBrush(background_colour))
                item.setFont(big_font)
                item.setTextAlignment(Qt.AlignCenter | Qt.AlignHCenter)
                item.setData(RoleHazard, hazard)
                item.setData(RoleExposure, exposure)
                self.tblFunctions1.setItem(
                    exposures.index(exposure), hazards.index(hazard), item)
        self.parent.pbnNext.setEnabled(False)
Ejemplo n.º 9
0
    def populate_function_table_1(self):
        """Populate the tblFunctions1 table with available functions."""
        hazards = deepcopy(hazard_all)
        exposures = exposure_all

        self.lblAvailableFunctions1.clear()
        self.tblFunctions1.clear()
        self.tblFunctions1.setColumnCount(len(hazards))
        self.tblFunctions1.setRowCount(len(exposures))
        for i in range(len(hazards)):
            hazard = hazards[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(hazard)))
            item.setText(hazard['name'].capitalize())
            item.setTextAlignment(Qt.AlignLeft)
            self.tblFunctions1.setHorizontalHeaderItem(i, item)
        for i in range(len(exposures)):
            exposure = exposures[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(exposure)))
            item.setText(exposure['name'].capitalize())
            self.tblFunctions1.setVerticalHeaderItem(i, item)
        developer_mode = setting('developer_mode', False, bool)
        for hazard in hazards:
            for exposure in exposures:
                item = QTableWidgetItem()
                if (exposure in hazard['disabled_exposures'] and not
                        developer_mode):
                    background_colour = unavailable_option_color
                    # Set it disable and un-selectable
                    item.setFlags(
                        item.flags() & ~
                        Qt.ItemIsEnabled & ~
                        Qt.ItemIsSelectable
                    )
                else:
                    background_colour = available_option_color
                item.setBackground(QBrush(background_colour))
                item.setFont(big_font)
                item.setTextAlignment(Qt.AlignCenter | Qt.AlignHCenter)
                item.setData(RoleHazard, hazard)
                item.setData(RoleExposure, exposure)
                self.tblFunctions1.setItem(
                    exposures.index(exposure), hazards.index(hazard), item)
        self.parent.pbnNext.setEnabled(False)
Ejemplo n.º 10
0
 def initTable(self):
     '''
     QTableWidget initialization
     '''
     header = QTableWidgetItem("  ")
     header.setTextAlignment(Qt.AlignLeft)
     self.dock.tableWidget.setHorizontalHeaderItem(0,header)
     header = QTableWidgetItem("FIELD")
     header.setTextAlignment(Qt.AlignLeft)
     self.dock.tableWidget.setHorizontalHeaderItem(1,header)
     header = QTableWidgetItem("VALUE")
     header.setTextAlignment(Qt.AlignLeft)
     self.dock.tableWidget.setHorizontalHeaderItem(2,header)
     self.dock.tableWidget.resizeColumnsToContents()
Ejemplo n.º 11
0
    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = NuevoNidoDialog()
            #QMessageBox.information(self.dlg, "Mensaje", "Esto solo debe correr una vez" )
            self.dlg.Cb_Estado.currentTextChanged.connect(
                self.evt_Cb_Estado_change)

        #Codigo que siempre se ejecuta la primera vez que se ejecuta
        #QMessageBox.information(self.dlg, "Mensaje", "Esto solo debe correr siempre" )

        #Crear conexion al Map Canvas
        mc = self.iface.mapCanvas()
        self.dlg.SpbD_Coord_X.setValue(mc.center().x())
        self.dlg.SpbD_Coord_Y.setValue(mc.center().y())
        self.dlg.DtE_Fecha.setDate(QDate.currentDate())

        #Revisar capas cargadas
        map_layers = []
        for lyr in mc.layers():
            map_layers.append(lyr.name())

        missing_layers = []
        if not "Avistamientos" in map_layers:
            missing_layers.append("Avistamientos")
        if not "Buffer Nidos" in map_layers:
            missing_layers.append("Buffer Nidos")
        if not "Buffer Lineal" in map_layers:
            missing_layers.append("Buffer Lineal")

        if missing_layers:
            mag = "Las siguientes capas falta en este proyecto"
            for lyr in missing_layers:
                mag += f"\n{lyr}"
            QMessageBox.critical(self.dlg, "Capas Faltantes", mag)
            return

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            #QMessageBox.information(self.dlg, "Mensaje", "Esto solo debe correr si presiona Ok" )
            lyrNido = QgsProject.instance().mapLayersByName("Avistamientos")[0]
            lyrBuffer = QgsProject.instance().mapLayersByName(
                "Buffer Nidos")[0]
            idxNidoId = lyrNido.fields().indexOf("nidoID")
            valNidoId = lyrNido.maximumValue(idxNidoId) + 1

            lyrLineal = QgsProject.instance().mapLayersByName(
                "Buffer Lineal")[0]

            #QMessageBox.information(self.dlg, "Mensaje", f"Nuevo Nido Id = {valNidoId}")
            valX = self.dlg.SpbD_Coord_X.value()
            valY = self.dlg.SpbD_Coord_Y.value()
            valEsp = self.dlg.Cb_Especie.currentText()
            valEst = self.dlg.Cb_Estado.currentText()
            valBuff = self.dlg.Spb_BuffDist.value()
            valFecha = self.dlg.DtE_Fecha.date()
            #QMessageBox.information(self.dlg, "Mensaje", f"Nuevo Nido Id = {valNidoId}\nCoord X = {valX}\nCoord Y = {valY}\nEspecie = {valEsp}\nEstado = {valEst}\nBuffer = {valBuff}\nFecha = {valFecha}")
            ftrNido = QgsFeature(lyrNido.fields())
            ftrNido.setAttribute("id", valNidoId)
            ftrNido.setAttribute("coord_x", valX)
            ftrNido.setAttribute("coord_y", valY)
            ftrNido.setAttribute("fecha", valFecha)
            ftrNido.setAttribute("especie", valEsp)
            ftrNido.setAttribute("estado", valEst)
            ftrNido.setAttribute("nidoID", valNidoId)
            ftrNido.setAttribute("dist_buf", valBuff)
            geom = QgsGeometry(QgsPoint(valX, valY))
            ftrNido.setGeometry(geom)
            pr = lyrNido.dataProvider()
            pr.addFeatures([ftrNido])
            lyrNido.reload()

            #Agregar el buffer
            pr = lyrBuffer.dataProvider()
            buffer = geom.buffer(valBuff, 10)
            ftrNido.setGeometry(buffer)
            pr.addFeatures([ftrNido])
            lyrBuffer.reload()

            dlgTabla = DlgTabla()
            dlgTabla.setWindowTitle(f"Tabla de Impactos para Nido {valNidoId}")
            bb = buffer.boundingBox()
            lineales = lyrLineal.getFeatures(bb)
            for lineal in lineales:
                valID = lineal.attribute("Proyecto")
                valTipo = lineal.attribute("Tipo")
                valDistancia = lineal.geometry().distance(geom)
                if valDistancia < valBuff:
                    fila = dlgTabla.Tbw_Impactos.rowCount()
                    dlgTabla.Tbw_Impactos.insertRow(fila)
                    dlgTabla.Tbw_Impactos.setItem(fila, 0,
                                                  QTableWidgetItem(str(valID)))
                    dlgTabla.Tbw_Impactos.setItem(fila, 1,
                                                  QTableWidgetItem(valTipo))
                    #dlgTabla.Tbw_Impactos.setItem(fila, 2, QTableWidgetItem(f"{valDistancia:.2f}")) #"{:.2f}".format(valDistancia)
                    twi = QTableWidgetItem(f"{valDistancia:.2f}")
                    twi.setTextAlignment(QtCore.Qt.AlignRight)
                    dlgTabla.Tbw_Impactos.setItem(fila, 2, twi)

            dlgTabla.Tbw_Impactos.sortItems(2)
            dlgTabla.show()
            dlgTabla.exec_()

        else:
            QMessageBox.information(
                self.dlg, "Mensaje",
                "Esto solo debe correr si presiona Cancel")
Ejemplo n.º 12
0
def update_srs_table_content(dockwidget, srs_table):
    with block_signals_to(dockwidget.QTableW_StraRS):
        # init table
        dockwidget.QTableW_StraRS.setRowCount(srs_table["row_count"])
        dockwidget.QTableW_StraRS.setColumnCount(srs_table["column_count"])

        # enter data onto Table
        for n, key in enumerate(srs_table["header"]):
            if key == "Pix Val":
                for m, item in enumerate(
                        srs_table["color_table"]["Pixel Value"]):
                    item_table = QTableWidgetItem(str(item))
                    item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    item_table.setTextAlignment(Qt.AlignCenter
                                                | Qt.AlignVCenter)
                    dockwidget.QTableW_StraRS.setItem(m, n, item_table)
            if key == "Color":
                for m in range(srs_table["row_count"]):
                    item_table = QTableWidgetItem()
                    item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    item_table.setBackground(
                        QColor(srs_table["color_table"]["Red"][m],
                               srs_table["color_table"]["Green"][m],
                               srs_table["color_table"]["Blue"][m],
                               srs_table["color_table"]["Alpha"][m]))
                    dockwidget.QTableW_StraRS.setItem(m, n, item_table)
            if key == "Num Samples":
                for m in range(srs_table["row_count"]):
                    item_table = QTableWidgetItem(srs_table["num_samples"][m])
                    item_table.setTextAlignment(Qt.AlignCenter
                                                | Qt.AlignVCenter)
                    if not srs_table["On"][m]:
                        item_table.setForeground(QColor("lightGrey"))
                        item_table.setFlags(Qt.ItemIsSelectable
                                            | Qt.ItemIsEnabled)
                    dockwidget.QTableW_StraRS.setItem(m, n, item_table)
            if key == "Std Error":
                for m in range(srs_table["row_count"]):
                    item_table = QTableWidgetItem(srs_table["std_error"][m])
                    item_table.setTextAlignment(Qt.AlignCenter
                                                | Qt.AlignVCenter)
                    if not srs_table["On"][m]:
                        item_table.setForeground(QColor("lightGrey"))
                        item_table.setFlags(Qt.ItemIsSelectable
                                            | Qt.ItemIsEnabled)
                    dockwidget.QTableW_StraRS.setItem(m, n, item_table)
            if key == "On":
                for m in range(srs_table["row_count"]):
                    item_table = QTableWidgetItem()
                    item_table.setFlags(Qt.ItemIsUserCheckable
                                        | Qt.ItemIsEnabled)
                    item_table.setTextAlignment(Qt.AlignCenter
                                                | Qt.AlignVCenter)
                    if srs_table["On"][m]:
                        item_table.setCheckState(Qt.Checked)
                    else:
                        item_table.setCheckState(Qt.Unchecked)
                    dockwidget.QTableW_StraRS.setItem(m, n, item_table)

        # hidden row labels
        dockwidget.QTableW_StraRS.verticalHeader().setVisible(False)
        # add Header
        dockwidget.QTableW_StraRS.setHorizontalHeaderLabels(
            srs_table["header"])
        # adjust size of Table
        dockwidget.QTableW_StraRS.resizeColumnsToContents()
        dockwidget.QTableW_StraRS.resizeRowsToContents()
        # set label total samples
        total_num_samples = sum(
            [int(x) for x in mask(srs_table["num_samples"], srs_table["On"])])
        dockwidget.TotalNumSamples.setText(str(total_num_samples))
        # set maximum and reset the value in progress bar status
        dockwidget.widget_generate_StraRS.QPBar_GenerateSampling.setValue(0)
        dockwidget.widget_generate_StraRS.QPBar_GenerateSampling.setMaximum(
            total_num_samples)
Ejemplo n.º 13
0
    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = NewRaptorDialog()
            self.dlg.cmbSpecies.currentTextChanged.connect(
                self.evt_cmbSpecies_changed)

        mc = self.iface.mapCanvas()
        self.dlg.spbLatitude.setValue(mc.center().y())
        self.dlg.spbLongitude.setValue(mc.center().x())
        self.dlg.dteLast.setDate(QDate.currentDate())

        map_layers = []
        for lyr in mc.layers():
            map_layers.append(lyr.name())
        missing_layers = []
        if not "Raptor Nests" in map_layers:
            missing_layers.append("Raptor Nests")
        if not "Raptor Buffer" in map_layers:
            missing_layers.append("Raptor Buffer")
        if not "Linear Buffer" in map_layers:
            missing_layers.append("Linear Buffer")
        if missing_layers:
            msg = "The following layers are missing from this project\n"
            for lyr in missing_layers:
                msg += "\n{}".format(lyr)
            QMessageBox.critical(self.dlg, "Missing Layers!", msg)
            return

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            lyrNest = QgsProject.instance().mapLayersByName("Raptor Nests")[0]
            lyrBuffer = QgsProject.instance().mapLayersByName(
                "Raptor Buffer")[0]
            lyrLinear = QgsProject.instance().mapLayersByName(
                "Linear Buffer")[0]
            idxNestId = lyrNest.fields().indexOf("Nest_ID")
            valNestId = lyrNest.maximumValue(idxNestId) + 1
            valLat = self.dlg.spbLatitude.value()
            valLng = self.dlg.spbLongitude.value()
            valSpecies = self.dlg.cmbSpecies.currentText()
            valBuffer = self.dlg.spbBuffer.value()
            valStatus = self.dlg.cmbStatus.currentText()
            valLast = self.dlg.dteLast.date()
            QMessageBox.information(
                self.dlg, "Message",
                "New Nest ID: {}\nLatitude: {}\nLongitude: {}\nSpecies: {}\nBuffer: {}\nStatus: {}\nLast survey: {}"
                .format(valNestId, valLat, valLng, valSpecies, valBuffer,
                        valStatus, valLast))
            ftrNest = QgsFeature(lyrNest.fields())
            ftrNest.setAttribute("lat_y_dd", valLat)
            ftrNest.setAttribute("long_x_dd", valLng)
            ftrNest.setAttribute("recentspec", valSpecies)
            ftrNest.setAttribute("buf_dist", valBuffer)
            ftrNest.setAttribute("recentstat", valStatus)
            ftrNest.setAttribute("lastsurvey", valLast)
            ftrNest.setAttribute("Nest_ID", valNestId)
            geom = QgsGeometry(QgsPoint(valLng, valLat))
            ftrNest.setGeometry(geom)
            pr = lyrNest.dataProvider()
            pr.addFeatures([ftrNest])
            lyrNest.reload()

            pr = lyrBuffer.dataProvider()
            buffer = geom.buffer(valBuffer, 10)
            ftrNest.setGeometry(buffer)
            pr.addFeatures([ftrNest])
            lyrBuffer.reload()

            dlgTable = DlgTable()
            dlgTable.setWindowTitle(
                "Impacts Table for Nest {}".format(valNestId))
            #Find linear projects that will be impacted by the Nest
            bb = buffer.boundingBox()
            linears = lyrLinear.getFeatures(bb)
            for linear in linears:
                valId = linear.attribute("Project")
                valType = linear.attribute("type")
                valDistance = linear.geometry().distance(
                    geom)  #geom is de geometry of the nestpoint
                if valDistance < valBuffer:
                    # populate the table with linear data
                    row = dlgTable.tblImpacts.rowCount()
                    dlgTable.tblImpacts.insertRow(row)
                    dlgTable.tblImpacts.setItem(row, 0,
                                                QTableWidgetItem(str(valId)))
                    dlgTable.tblImpacts.setItem(row, 1,
                                                QTableWidgetItem(valType))
                    twi = QTableWidgetItem("{:4.5f}".format(valDistance))
                    twi.setTextAlignment(QtCore.Qt.AlignRight)
                    dlgTable.tblImpacts.setItem(row, 2, twi)
            dlgTable.tblImpacts.sortItems(2)
            dlgTable.show()
            dlgTable.exec_()

        else:
            QMessageBox.information(self.dlg, "Message",
                                    "Should only run if cancelled")
Ejemplo n.º 14
0
    def set_pixel_table(self):
        # clear table
        self.PixelTable.clear()
        self.PixelTable.setRowCount(0)
        self.PixelTable.setColumnCount(0)
        if not self.thematic_file_classes:
            return

        with block_signals_to(self.PixelTable):
            header = ["", "class value", "select"]
            row_length = len(self.pixel_classes)
            # init table
            self.PixelTable.setRowCount(row_length)
            self.PixelTable.setColumnCount(3)
            self.PixelTable.horizontalHeader().setMinimumSectionSize(45)
            # hidden row labels
            self.PixelTable.verticalHeader().setVisible(False)
            # add Header
            self.PixelTable.setHorizontalHeaderLabels(header)
            # insert items
            for col_idx, header in enumerate(header):
                if header == "":
                    for row_idx, pixel in enumerate(self.pixel_classes):
                        item_table = QTableWidgetItem()
                        item_table.setFlags(item_table.flags()
                                            & ~Qt.ItemIsSelectable)
                        item_table.setBackground(
                            QColor(pixel["color"]["R"], pixel["color"]["G"],
                                   pixel["color"]["B"], pixel["color"]["A"]))
                        self.PixelTable.setItem(row_idx, col_idx, item_table)
                if header == "class value":
                    for row_idx, pixel in enumerate(self.pixel_classes):
                        item_table = QTableWidgetItem(str(pixel["value"]))
                        item_table.setFlags(item_table.flags()
                                            & ~Qt.ItemIsSelectable)
                        item_table.setFlags(item_table.flags()
                                            & ~Qt.ItemIsEditable)
                        item_table.setTextAlignment(Qt.AlignCenter
                                                    | Qt.AlignVCenter)
                        self.PixelTable.setItem(row_idx, col_idx, item_table)
                if header == "select":
                    for row_idx, pixel in enumerate(self.pixel_classes):
                        item_table = QTableWidgetItem()
                        item_table.setFlags(item_table.flags()
                                            | Qt.ItemIsUserCheckable)
                        item_table.setFlags(item_table.flags()
                                            | Qt.ItemIsEnabled)
                        item_table.setFlags(item_table.flags()
                                            & ~Qt.ItemIsSelectable)
                        item_table.setTextAlignment(Qt.AlignCenter
                                                    | Qt.AlignVCenter)
                        if pixel["select"]:
                            item_table.setCheckState(Qt.Checked)
                        else:
                            item_table.setCheckState(Qt.Unchecked)
                        self.PixelTable.setItem(row_idx, col_idx, item_table)

            # adjust size of Table
            self.PixelTable.resizeColumnsToContents()
            self.PixelTable.resizeRowsToContents()
            # adjust the editor block based on table content
            table_width = self.PixelTable.horizontalHeader().length() + 40
            self.TableBlock.setMaximumWidth(table_width)
            self.TableBlock.setMinimumWidth(table_width)
Ejemplo n.º 15
0
def create_label_item(title):
    item = QTableWidgetItem(title)
    item.setTextAlignment(Qt.AlignCenter)
    item.setFlags(Qt.NoItemFlags)
    return item
Ejemplo n.º 16
0
    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = NewRaptorDialog()
            self.dlg.cmbSpecies.currentTextChanged.connect(
                self.evt_cmbSpecies_changed)

        QMessageBox.information(self.dlg, "Message", "Should run every time")
        # get coordinates from center of mapCanvas
        mc = self.iface.mapCanvas()
        self.dlg.spbLatitude.setValue(mc.center().y())
        self.dlg.spbLongitude.setValue(mc.center().x())

        # set current date in the dialog
        self.dlg.dteLast.setDate(QDate.currentDate())

        # check if layer in which we want write data to exists
        # first create list of layers that exist in project
        map_layers = []
        for lyr in mc.layers():
            map_layers.append(lyr.name())
        QMessageBox.information(self.dlg, "Layers", str(map_layers))

        # check for layers that are necessary to run plugin in list above, if they don't exist inform user about it
        missing_layers = []
        if not "Raptor Nests" in map_layers:
            missing_layers.append("Raptor Nests")
        if not "Raptor Buffer" in map_layers:
            missing_layers.append("Raptor Nests")
        if not "Linear Buffer" in map_layers:
            missing_layers.append("Linear Buffer")
        if missing_layers:
            msg = "The follwoing layers are missing from this project\n"
            for lyr in missing_layers:
                msg += "\n{}".format(lyr)
            QMessageBox.critical(self.dlg, "Missing layers", msg)
            # stop execution of method by ending it with return
            return

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            #             QMessageBox.information(self.dlg, "Message", "Should run if OK button clicked")

            #create reference to nests table
            lyrNests = QgsProject.instance().mapLayersByName("Raptor Nests")[0]
            lyrBuffer = QgsProject.instance().mapLayersByName(
                "Raptor Buffer")[0]

            #create reference to linear buffer table
            lyrLinear = QgsProject.instance().mapLayersByName(
                "Linear Buffer")[0]
            #get maximum value of ide to increment it properly
            idxNestID = lyrNests.fields().indexOf("Nest_ID")
            valNestID = lyrNests.maximumValue(idxNestID) + 1
            valLat = self.dlg.spbLatitude.value()
            valLng = self.dlg.spbLongitude.value()
            valSpecies = self.dlg.cmbSpecies.currentText()
            valBuffer = self.dlg.spbBuffer.value()
            valStatus = self.dlg.cmbStatus.currentText()
            valLast = self.dlg.dteLast.date()
            QMessageBox.information(
                self.dlg, "Message",
                "New Nest ID: {}\n\nLatitude: {}\nLongitude: {}\nSpecies: {}\nBuffer: {}\nStatus: {}\nLast Survey: {}"
                .format(valNestID, valLat, valLng, valSpecies, valBuffer,
                        valStatus, valLast))

            #create new feature based on Nests layer
            ftrNest = QgsFeature(lyrNests.fields())
            ftrNest.setAttribute("lat_y_dd", valLat)
            ftrNest.setAttribute("long_x_dd", valLng)
            ftrNest.setAttribute("recentspec", valSpecies)
            ftrNest.setAttribute("buf_dist", valBuffer)
            ftrNest.setAttribute("recentstat", valStatus)
            ftrNest.setAttribute("lastsurvey", valLast)
            ftrNest.setAttribute("Nest_ID", valNestID)
            geom = QgsGeometry(QgsPoint(valLng, valLat))
            ftrNest.setGeometry(geom)

            #insert feature into layer, using data provider
            pr = lyrNests.dataProvider()
            pr.addFeatures([ftrNest])
            lyrNests.reload()

            #code to insert the buffer
            pr = lyrBuffer.dataProvider()
            buffer = geom.buffer(valBuffer, 10)
            ftrNest.setGeometry(buffer)
            pr.addFeatures([ftrNest])
            lyrBuffer.reload()

            #code to popup table from impact_table.ui
            dlgTable = DlgTable()
            dlgTable.setWindowTitle(
                "Impacts Table for Nest{}".format(valNestID))

            #create bounding box to limit selection and improve algorithm speed
            bb = buffer.boundingBox()

            #Find linear projects that will be impacted and report
            linears = lyrLinear.getFeatures(bb)
            for linear in linears:
                valID = linear.attribute("Project")
                valType = linear.attribute("type")
                #return distance beetween linear buffer and the nest
                valDistance = linear.geometry().distance(geom)
                if valDistance < valBuffer:
                    #Populate table with linear data
                    row = dlgTable.tblImpacts.rowCount()
                    dlgTable.tblImpacts.insertRow(row)
                    dlgTable.tblImpacts.setItem(row, 0,
                                                QTableWidgetItem(str(valID)))
                    dlgTable.tblImpacts.setItem(row, 1,
                                                QTableWidgetItem(valType))
                    twi = QTableWidgetItem(str("{:4.5f}".format(valDistance)))
                    twi.setTextAlignment(QtCore.Qt.AlignRight)
                    dlgTable.tblImpacts.setItem(row, 2, twi)
                    #sort data in table
                    dlgTable.tblImpacts.sortItems(2)
            dlgTable.show()
            dlgTable.exec_()

        else:
            QMessageBox.information(self.dlg, "Message",
                                    "Should only run if cancelled")
Ejemplo n.º 17
0
    def create_table(self):
        from AcATaMa.gui.acatama_dockwidget import AcATaMaDockWidget as AcATaMa

        header = ["Classification Name", "Color", "Thematic Class", ""]
        # clear table
        self.tableBtnsConfig.clear()
        # init table
        self.tableBtnsConfig.setRowCount(len(self.table_buttons))
        self.tableBtnsConfig.setColumnCount(4)
        # hidden row labels
        self.tableBtnsConfig.verticalHeader().setVisible(False)
        # add Header
        self.tableBtnsConfig.setHorizontalHeaderLabels(header)
        # insert items
        for n, h in enumerate(header):
            if h == "Classification Name":
                for m, (key, item) in enumerate(self.table_buttons.items()):
                    if m + 1 in self.buttons_config:
                        item_table = QTableWidgetItem(
                            self.buttons_config[m + 1]["name"])
                    else:
                        item_table = QTableWidgetItem(str(item))
                    item_table.setTextAlignment(Qt.AlignCenter
                                                | Qt.AlignVCenter)
                    item_table.setToolTip(
                        "Classification button ID: {}".format(key))
                    self.tableBtnsConfig.setItem(m, n, item_table)
            if h == "Color":
                for m, item in enumerate(self.table_buttons.values()):
                    item_table = QTableWidgetItem()
                    if m + 1 in self.buttons_config:
                        item_table.setBackground(
                            QColor(self.buttons_config[m + 1]["color"]))
                    item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    item_table.setTextAlignment(Qt.AlignCenter
                                                | Qt.AlignVCenter)
                    self.tableBtnsConfig.setItem(m, n, item_table)
            if h == "Thematic Class":
                for m, item in enumerate(self.table_buttons.values()):
                    if valid_file_selected_in(
                            AcATaMa.dockwidget.QCBox_ThematicRaster):
                        if m + 1 in self.buttons_config and self.buttons_config[
                                m + 1]["thematic_class"] is not None:
                            item_table = QTableWidgetItem(
                                self.buttons_config[m + 1]["thematic_class"])
                        else:
                            item_table = QTableWidgetItem(str(item))
                        item_table.setToolTip(
                            "Click to open the pixel value/color table of the thematic classes"
                        )
                    else:
                        item_table = QTableWidgetItem("none")
                        item_table.setFlags(Qt.ItemIsSelectable
                                            | Qt.ItemIsEnabled)
                        item_table.setForeground(QColor("lightGrey"))
                        item_table.setToolTip(
                            "No thematic layer, if you want enable the thematic classes,\n"
                            "select first a valid thematic layer in thematic tab"
                        )
                        item_h = QTableWidgetItem(h)
                        item_h.setForeground(QColor("lightGrey"))
                        self.tableBtnsConfig.setHorizontalHeaderItem(2, item_h)

                    item_table.setTextAlignment(Qt.AlignCenter
                                                | Qt.AlignVCenter)
                    self.tableBtnsConfig.setItem(m, n, item_table)
            if h == "":
                for m, item in enumerate(self.table_buttons.values()):
                    item_table = QTableWidgetItem()
                    path = ':/plugins/AcATaMa/icons/trash.svg'
                    icon = QIcon(path)
                    item_table.setIcon(icon)
                    item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    item_table.setTextAlignment(Qt.AlignCenter
                                                | Qt.AlignVCenter)
                    item_table.setToolTip("Clean this row")
                    self.tableBtnsConfig.setItem(m, n, item_table)

        # set the minimum width to 0 for headers
        self.tableBtnsConfig.horizontalHeader().setMinimumSectionSize(0)
        # adjust size of Table
        self.tableBtnsConfig.resizeColumnsToContents()
        self.tableBtnsConfig.resizeRowsToContents()
        # adjust the dialog based on table content
        dialog_width = self.tableBtnsConfig.horizontalHeader().length() + 50
        self.resize(dialog_width, self.height())
Ejemplo n.º 18
0
    def _edit_row(self, row, data):
        """Internal function to edit a row."""
        self._layer = None
        for i, key in enumerate(data.keys()):
            value = data[key]
            cell = QTableWidgetItem()

            input_type = self.definitions.layer_config[key]['type']

            if input_type == InputType.Layer:
                layer = QgsProject.instance().mapLayer(value)
                self._layer = layer
                cell.setText(layer.name())
                cell.setData(Qt.UserRole, layer.id())
                cell.setData(
                    Qt.ToolTipRole, '{} ({})'.format(layer.name(),
                                                     layer.crs().authid()))
                cell.setIcon(QgsMapLayerModel.iconForLayer(layer))

            elif input_type == InputType.Field:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

                # Get the icon for the field
                if self._layer:
                    index = self._layer.fields().indexFromName(value)
                    if index >= 0:
                        cell.setIcon(self._layer.fields().iconForField(index))

            elif input_type == InputType.Fields:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

            elif input_type == InputType.Color:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)
                if value:
                    cell.setData(Qt.DecorationRole, QColor(value))

            elif input_type == InputType.CheckBox:
                if value:
                    cell.setText('✓')
                    cell.setData(Qt.UserRole, True)
                    cell.setData(Qt.ToolTipRole, tr('True'))
                else:
                    cell.setText('')
                    cell.setData(Qt.UserRole, False)
                    cell.setData(Qt.ToolTipRole, tr('False'))
                cell.setTextAlignment(Qt.AlignCenter)

            elif input_type == InputType.List:
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)
                items = self.definitions.layer_config[key].get('items')
                if items:
                    for item_enum in items:
                        if item_enum.value['data'] == value:
                            text = item_enum.value['label']
                            icon = item_enum.value.get('icon')
                            break
                    else:
                        raise Exception(
                            'Error with list value="{}"'.format(value))
                    cell.setText(text)
                    if icon:
                        cell.setIcon(QIcon(icon))
                else:
                    cell.setText(value)

            elif input_type == InputType.SpinBox:
                cell.setText(str(value))
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

            elif input_type == InputType.Text:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

            else:
                raise Exception(
                    'InputType "{}" not implemented'.format(input_type))

            self.table.setItem(row, i, cell)
        self._layer = None
        self.table.clearSelection()
Ejemplo n.º 19
0
    def _edit_row(self, row, data):
        """Internal function to edit a row."""
        self._layer = None
        for i, key in enumerate(data.keys()):
            value = data[key]
            cell = QTableWidgetItem()

            input_type = self.definitions.layer_config[key]['type']

            if self._layer and hasattr(value, '__call__'):
                # Value is a for now a function, we need to evaluate it
                value = value(self._layer)

            if input_type == InputType.Layer:
                layer = QgsProject.instance().mapLayer(value)
                self._layer = layer
                cell.setText(layer.name())
                cell.setData(Qt.UserRole, layer.id())
                cell.setData(
                    Qt.ToolTipRole, '{} ({})'.format(layer.name(),
                                                     layer.crs().authid()))
                cell.setIcon(QgsMapLayerModel.iconForLayer(layer))

            elif input_type == InputType.Layers:
                names = []
                for layer in value:
                    if layer != '':
                        vector = QgsProject.instance().mapLayer(layer)
                        if vector:
                            names.append(vector.name())
                display = ' ,'.join(names)
                cell.setText(display)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, display)

            elif input_type == InputType.Field:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

                # Get the icon for the field
                if self._layer:
                    index = self._layer.fields().indexFromName(value)
                    if index >= 0:
                        cell.setIcon(self._layer.fields().iconForField(index))

            elif input_type == InputType.Fields:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

            elif input_type == InputType.Color:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)
                if value:
                    cell.setData(Qt.DecorationRole, QColor(value))

            elif input_type == InputType.CheckBox:
                if value:
                    cell.setText('✓')
                    cell.setData(Qt.UserRole, True)
                    cell.setData(Qt.ToolTipRole, tr('True'))
                else:
                    cell.setText('')
                    cell.setData(Qt.UserRole, False)
                    cell.setData(Qt.ToolTipRole, tr('False'))
                cell.setTextAlignment(Qt.AlignCenter)

            elif input_type == InputType.Json:
                if value:
                    cell.setText(json.dumps(value))
                    cell.setData(Qt.UserRole, value)
                    cell.setData(Qt.ToolTipRole, value)
                else:
                    cell.setText('')
                    cell.setData(Qt.UserRole, '')
                    cell.setData(Qt.ToolTipRole, '')

            elif input_type == InputType.List:
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)
                items = self.definitions.layer_config[key].get('items')
                if items:
                    for item_enum in items:
                        if item_enum.value['data'] == value:
                            text = item_enum.value['label']
                            icon = item_enum.value.get('icon')
                            break
                    else:
                        msg = 'Error with value = "{}" in list "{}"'.format(
                            value, key)
                        LOGGER.critical(msg)
                        raise Exception(msg)
                    cell.setText(text)
                    if icon:
                        cell.setIcon(QIcon(icon))
                else:
                    cell.setText(value)

            elif input_type == InputType.SpinBox:
                unit = self.definitions.layer_config[key].get('unit')
                if unit:
                    display = '{}{}'.format(value, unit)
                else:
                    display = '{}'.format(value)
                cell.setText(display)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

            elif input_type == InputType.Text:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

            elif input_type == InputType.MultiLine:
                cell.setText(value)
                cell.setData(Qt.UserRole, value)
                cell.setData(Qt.ToolTipRole, value)

            elif input_type == InputType.Collection:
                json_dump = json.dumps(value)
                cell.setText(json_dump)
                cell.setData(Qt.UserRole, value)
                function = self.definitions.layer_config[key][
                    'represent_value']
                cell.setData(Qt.ToolTipRole, function(value))

            else:
                raise Exception(
                    'InputType "{}" not implemented'.format(input_type))

            self.table.setItem(row, i, cell)
        self._layer = None
        self.table.clearSelection()
Ejemplo n.º 20
0
    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = NewRaptorDialog()

            #
            self.dlg.cmbSpecies.currentTextChanged.connect(
                self.evt_cmbSpecies_changed)

        mc = self.iface.mapCanvas()

        self.dlg.spbLatitude.setValue(mc.center().y())
        self.dlg.spbLongitude.setValue(mc.center().x())
        self.dlg.dteLast.setDate(QDate.currentDate())

        # Lista de camada do mapa
        map_layers = []
        for lyr in mc.layers():
            map_layers.append(lyr.name())

        # Coloca o nome dos layrs em uma caixa de mensagem, com o titulo camadas
        #QMessageBox.information(self.dlg, "Layers", str(map_layers))

        # cria uma caixa de mensagem caso não achar alguams das layrs descritas abaixo
        missing_layers = []
        if not 'Raptor Nests' in map_layers:
            missing_layers.append('Raptor Nests')
        if not 'Raptor Buffer' in map_layers:
            missing_layers.append('Raptor Buffer')
        if not 'Linear Buffer' in map_layers:
            missing_layers.append('Linear Buffer')

        if missing_layers:
            msg = 'The following layres are missing from ths project\n'
            for lyr in missing_layers:
                msg += f'\n {lyr}'
            QMessageBox.critical(self.dlg, 'Missing layers', msg)
            # o return barra a execução das demais linhas de códigos
            return

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.

            # irá retornar uma lista com o as camdas com nome Raptor Nests, mas iremos pegar apenas a primeira camadd
            lyrNests = QgsProject.instance().mapLayersByName('Raptor Nests')[0]
            lyrBuffer = QgsProject.instance().mapLayersByName(
                'Raptor Buffer')[0]
            lyrLinear = QgsProject.instance().mapLayersByName(
                'Linear Buffer')[0]
            # Irá pegar o ultimo valor de índice
            idxNestID = lyrNests.fields().indexOf('Nest_ID')
            valNestID = lyrNests.maximumValue(idxNestID) + 1

            # Irá pegar os valores que foram digitados na caixa de texto
            valLat = self.dlg.spbLatitude.value()
            valLng = self.dlg.spbLongitude.value()
            valSpecies = self.dlg.cmbSpecies.currentText()
            valBuffer = self.dlg.spbBuffer.value()
            valStatus = self.dlg.cmbStatus.currentText()
            valLast = self.dlg.dteLast.date()
            QMessageBox.information(
                self.dlg, 'Message',
                f'New Nest ID: {valNestID}\n \nLatitude: {valLat} '
                f'\nLongitude: {valLng} \nSpecies: {valSpecies} '
                f'\nBuffer: {valBuffer} \nStatus: {valStatus} \nLast: {valLast}'
            )
            # cria um novo objeto da classe QgsFeature, no qual a classe terá os mesmoa campos do lyrnet.fildes
            # (objeto da Layer Raptor Nests)
            ftrNest = QgsFeature(lyrNests.fields())
            # Irá começar a adicoanr atributos de acordo com o nome dos campos da layer Raptor Nests
            ftrNest.setAttribute('lat_y_dd', valLat)
            ftrNest.setAttribute('long_x_dd', valLng)
            ftrNest.setAttribute('recentspec', valSpecies)
            ftrNest.setAttribute('buf_dist', valBuffer)
            ftrNest.setAttribute('recentstat', valStatus)
            ftrNest.setAttribute('lastsurvey', valLast)
            ftrNest.setAttribute('Nest_ID', valNestID)

            # colcoando o tipo de geometria
            geom = QgsGeometry(QgsPoint(valLng, valLat))
            ftrNest.setGeometry(geom)

            # Cada tipo de dados pode ter um provedor diferente, o qgis tem extensões para varios tipos de provedor,
            # a função abaixo pega o provedor e inclui os dados de acordo com o proveor
            pr = lyrNests.dataProvider()
            pr.addFeatures([ftrNest])
            lyrNests.reload()

            # Adiconando a camada de buffer
            pr = lyrBuffer.dataProvider()
            buffer = geom.buffer(valBuffer, 10)
            ftrNest.setGeometry(buffer)
            pr.addFeatures([ftrNest])
            lyrBuffer.reload()

            dlgTable = DlgTable()
            dlgTable.setWindowTitle(f"Impacts Table for Nest {valNestID}")

            # Find linear projects that will impacted and report then in the table
            bb = buffer.boundingBox()
            linears = lyrLinear.getFeatures(bb)
            for linear in linears:
                valID = linear.attribute('Project')
                valType = linear.attribute('type')
                valDistance = linear.geometry().distance(geom)
                if valDistance < valBuffer:
                    #populate table with Linear data
                    row = dlgTable.tblImpacts.rowCount()
                    dlgTable.tblImpacts.insertRow(row)
                    dlgTable.tblImpacts.setItem(row, 0,
                                                QTableWidgetItem(str(valID)))
                    dlgTable.tblImpacts.setItem(row, 1,
                                                QTableWidgetItem(valType))
                    twi = QTableWidgetItem(f"{valDistance:4.5f}")
                    twi.setTextAlignment(QtCore.Qt.AlignRight)
                    dlgTable.tblImpacts.setItem(row, 2, twi)

            dlgTable.tblImpacts.sortItems(2)
            dlgTable.show()
            dlgTable.exec_()

        else:
            QMessageBox.information(self.dlg, "Message",
                                    "Should only run if cancelled")