Exemplo n.º 1
0
    def setTableContent(self):
        numOutputs = 0
        for output in self.alg.outputs:
            if isinstance(output, (OutputVector, OutputRaster)):
                if not output.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    numOutputs += 1
        self.tblStyles.setRowCount(numOutputs)

        i = 0
        for output in self.alg.outputs:
            if isinstance(output, (OutputVector, OutputRaster)):
                if not output.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    item = QTableWidgetItem(output.description() + '<' +
                                            output.__class__.__name__ + '>')
                    item.setFlags(Qt.ItemIsEnabled)
                    self.tblStyles.setItem(i, 0, item)
                    item = RenderingStyleFilePanel()
                    style = \
                        RenderingStyles.getStyle(self.alg.id(),
                                                 output.name())
                    if style:
                        item.setText(str(style))
                    self.valueItems[output.name()] = item
                    self.tblStyles.setCellWidget(i, 1, item)
                    self.tblStyles.setRowHeight(i, 22)
            i += 1
Exemplo n.º 2
0
    def setTableContent(self):
        numOutputs = 0
        for output in self.alg.outputDefinitions():
            if isinstance(output, (QgsProcessingOutputVectorLayer,
                                   QgsProcessingOutputRasterLayer)):
                numOutputs += 1
        self.tblStyles.setRowCount(numOutputs)

        i = 0
        for output in self.alg.outputDefinitions():
            if isinstance(output, (QgsProcessingOutputVectorLayer,
                                   QgsProcessingOutputRasterLayer)):
                item = QTableWidgetItem(output.description() + '<' +
                                        output.__class__.__name__ + '>')
                item.setFlags(Qt.ItemIsEnabled)
                self.tblStyles.setItem(i, 0, item)
                item = RenderingStyleFilePanel()
                style = \
                    RenderingStyles.getStyle(self.alg.id(),
                                             output.name())
                if style:
                    item.setText(str(style))
                self.valueItems[output.name()] = item
                self.tblStyles.setCellWidget(i, 1, item)
                self.tblStyles.setRowHeight(i, 22)
            i += 1
 def applyConceptToColumn(self,costumURI=False):
     fieldnames = [field.name() for field in self.layer.fields()]
     item=QTableWidgetItem(self.searchResult.currentItem().text()[0:self.searchResult.currentItem().text().rfind('(')-1])
     #item.setFlags(QtCore.Qt.ItemIsEnabled)
     row = self.enrichtable.rowCount() 
     self.enrichtable.insertRow(row)
     self.enrichtable.setItem(row,0,item)
     item=QTableWidgetItem()
     item.setData(1,self.searchResult.currentItem().data(1))
     item.setText(self.searchResult.currentItem().text())
     self.enrichtable.setItem(row,1,item)
     item=QTableWidgetItem()
     item.setText(self.triplestoreconf[self.tripleStoreEdit.currentIndex()+1]["endpoint"])
     self.enrichtable.setItem(row,2,item)
     cbox=QComboBox()
     cbox.addItem("Get Remote")
     cbox.addItem("No Enrichment")
     cbox.addItem("Exclude")
     self.enrichtable.setCellWidget(row,3,cbox)
     cbox=QComboBox()	
     cbox.addItem("Enrich Value")	
     cbox.addItem("Enrich URI")	
     cbox.addItem("Enrich Both")	
     self.enrichtable.setCellWidget(row,4,cbox)
     cbox=QComboBox()
     for fieldd in fieldnames:
         cbox.addItem(fieldd)	
     self.enrichtable.setCellWidget(row,5,cbox)
     itemm=QTableWidgetItem("http://www.w3.org/2000/01/rdf-schema#label")
     self.enrichtable.setItem(row,6,itemm) 
     itemm=QTableWidgetItem(self.conceptSearchEdit.text())
     self.enrichtable.setItem(row,7,itemm)
     itemm=QTableWidgetItem("")
     self.enrichtable.setItem(row,8,itemm)
     self.close()
Exemplo n.º 4
0
    def setTableContent(self):
        numOutputs = 0
        for output in self.alg.outputs:
            if isinstance(output, (OutputVector, OutputRaster)):
                if not output.hidden:
                    numOutputs += 1
        self.tblStyles.setRowCount(numOutputs)

        i = 0
        for output in self.alg.outputs:
            if isinstance(output, (OutputVector, OutputRaster)):
                if not output.hidden:
                    item = QTableWidgetItem(output.description + '<'
                                            + output.__class__.__name__ + '>')
                    item.setFlags(Qt.ItemIsEnabled)
                    self.tblStyles.setItem(i, 0, item)
                    item = RenderingStyleFilePanel()
                    style = \
                        RenderingStyles.getStyle(self.alg.commandLineName(),
                                                 output.name)
                    if style:
                        item.setText(unicode(style))
                    self.valueItems[output.name] = item
                    self.tblStyles.setCellWidget(i, 1, item)
                    self.tblStyles.setRowHeight(i, 22)
            i += 1
Exemplo n.º 5
0
    def setTableContent(self):
        numOutputs = 0
        for output in self.alg.outputs:
            if isinstance(output, (OutputVector, OutputRaster)):
                if not output.hidden:
                    numOutputs += 1
        self.tblStyles.setRowCount(numOutputs)

        i = 0
        for output in self.alg.outputs:
            if isinstance(output, (OutputVector, OutputRaster)):
                if not output.hidden:
                    item = QTableWidgetItem(output.description + '<' +
                                            output.__class__.__name__ + '>')
                    item.setFlags(Qt.ItemIsEnabled)
                    self.tblStyles.setItem(i, 0, item)
                    item = RenderingStyleFilePanel()
                    style = \
                        RenderingStyles.getStyle(self.alg.commandLineName(),
                                                 output.name)
                    if style:
                        item.setText(str(style))
                    self.valueItems[output.name] = item
                    self.tblStyles.setCellWidget(i, 1, item)
                    self.tblStyles.setRowHeight(i, 22)
            i += 1
Exemplo n.º 6
0
 def importValues(self, table, strValue):
     rowValues = strValue.split(";")
     for r in range(len(rowValues)):
         row = rowValues[r]
         if len(row) > 2:
             colValues = (row[1:len(row) - 1]).split("-")
             for c in range(len(colValues)):
                 col = colValues[c]
                 item = QTableWidgetItem()
                 item.setText(col)
                 self.tableWidget.setItem(r, c, item)
Exemplo n.º 7
0
 def display_action(self, row, level, message):
     """ Display the action if needed to the user with a color. """
     cell = QTableWidgetItem()
     cell.setText(message)
     cell.setToolTip(message)
     if level == Qgis.Success:
         color = QColor("green")
     elif level == Qgis.Critical:
         color = QColor("red")
     else:
         color = QColor("orange")
     cell.setData(Qt.ForegroundRole, QVariant(color))
     self.table.setItem(row, 2, cell)
Exemplo n.º 8
0
 def createAttributeItems(self, fullTableName, currentDict, qmlDict, count, colour = None):
     """
     Creates a QTableWidgetItem for each attribute.
     The cell can have different types according to the data type used (i.e QCombobox, QLineEdit or QListWidget)
     """
     if fullTableName in currentDict:
         for attr in currentDict[fullTableName]:
             self.attributeTableWidget.insertRow(count)
             item = QTableWidgetItem()
             item.setText(attr)
             if colour:
                 item.setBackground(colour)
             self.attributeTableWidget.setItem(count, 0, item)
             #creating the specific cell widget. It can be a QCombobox, a QLineEdit or a QListWidget
             self.createCellWidget(qmlDict, attr, count)
             count+=1
 def selectSource(self): 
     '''
     source feature selection procedure
     '''
     if self.layerHighlighted:
         self.resetSource()
     try:
         self.dock.tableWidget.itemChanged.disconnect(self.highLightCellOverride)
     except:
         pass
     #take first selected feature as source feature
     self.sourceFeat = self.selectedFeature
     #hightlight source feature with rubberband
     self.sourceEvid.setToGeometry(self.sourceFeat.geometry(),self.selectedLayer)
     #get current layer attributes labels list
     field_names = self.scanLayerFieldsNames(self.selectedLayer)
     field_types = self.scanLayerFieldsTypes(self.selectedLayer)
     self.sourceAttrsTab=[]
     self.dock.tableWidget.setRowCount(len(field_names))
     #loading attributes labels and values in QTableWidget
     for n in range(0,len(field_names)):
             item=QTableWidgetItem()
             item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
             item.setCheckState(Qt.Unchecked)
             item.setText("")
             #set first column as checkbox
             self.dock.tableWidget.setItem(n,0,item)
             #set second colunm as attribute label as qcombobox widget
             self.dock.tableWidget.setCellWidget(n,1,self.setComboField(field_names[n],field_types[n],self.canvas.currentLayer()))
             #set third column as attribute value
             item = QTableWidgetItem()
             item.setData(Qt.DisplayRole,self.sourceFeat.attributes()[n])
             self.dock.tableWidget.setItem(n,2,item)
     #resize table to contents
     self.dock.tableWidget.resizeColumnsToContents()
     self.dock.tableWidget.horizontalHeader().setStretchLastSection(True)
     #procedure to recover same field selection if current source feature has the same layer of the precedent one
     if self.selectedLayer.id() != self.activeLayer:
         self.sourceAttrs={}
         self.activeLayer = self.selectedLayer.id()
     else:
         for Attr in self.sourceAttrs:
             self.dock.tableWidget.item(Attr,0).setCheckState(Qt.Checked)
     #Enable button to apply or reset
     self.dock.ResetSource.setEnabled(True)
     self.dock.tableWidget.itemChanged.connect(self.highLightCellOverride)
     self.checkOnLayerChange(self.canvas.currentLayer())
Exemplo n.º 10
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)
Exemplo n.º 11
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)
Exemplo n.º 12
0
def addSettingsToRow(settings, out_table):
    s = settings
    row = out_table.rowCount()
    out_table.insertRow(row)
    s = settings
    # insert values
    for i, value in enumerate([
            s.layerName, s.startTimeAttribute, s.endTimeAttribute, s.isEnabled,
            s.layerId, s.timeFormat,
            str(s.offset), s.interpolationEnabled, s.idAttribute,
            s.interpolationMode, not s.geometriesCount, s.accumulate,
            s.resetSubsetString
    ]):
        item = QTableWidgetItem()
        if type(value) != bool:
            item.setText(value)
        else:
            item.setCheckState(Qt.Checked if value else Qt.Unchecked)
        out_table.setItem(row, i, item)
Exemplo n.º 13
0
def addSettingsToRow(settings, out_table):
    s = settings
    row = out_table.rowCount()
    out_table.insertRow(row)
    s = settings
    # insert values
    for i, value in enumerate([s.layerName, s.startTimeAttribute, s.endTimeAttribute,
                               s.isEnabled, s.layerId, s.timeFormat,
                               str(s.offset), s.interpolationEnabled, s.idAttribute,
                               s.interpolationMode,
                               not s.geometriesCount,
                               s.accumulate,
                                s.resetSubsetString]):
        item = QTableWidgetItem()
        if type(value) != bool:
            item.setText(value)
        else:
            item.setCheckState(Qt.Checked if value else Qt.Unchecked)
        out_table.setItem(row, i, item)
Exemplo n.º 14
0
    def restoreState(self,layer,table):
        if layer.id() in self.states.keys():
            table.blockSignals(True)
            #clear dock widget
            while table.rowCount()>0:
                table.removeRow(0)
            #add rows
            table.setRowCount(len(self.states[layer.id()]))
            for n in range(0, len(self.states[layer.id()])):
                row = self.states[layer.id()][n]
                #set first column as checkbox
                item=QTableWidgetItem()
                item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
                if row[0]:
                    item.setCheckState(Qt.Checked)
                else:
                    item.setCheckState(Qt.Unchecked)
                item.setText("")
                table.setItem(n,0,item)
                #set second column as combobox
                combo = QComboBox();
                combo.addItems(row[1])
                #print (row[1],row[2])
                combo.setCurrentIndex(row[2])
                table.setCellWidget(n,1,combo)
                #set third column as attribute value
                item = QTableWidgetItem(row[3])
                item.setData(Qt.DisplayRole,row[4])
                if row[5]:
                    item.setForeground(QBrush(QColor(0,0,0)))
                else:
                    item.setForeground(QBrush(QColor(130,130,130)))
                if row[6]:
                    item.setBackground(QBrush(QColor(183,213,225)))
                table.setItem(n,2,item)

            table.blockSignals(False)
            return True

        else:
            return None
Exemplo n.º 15
0
    def request_finished(self, row):
        """ Dispatch the answer to update the GUI. """
        cell = QTableWidgetItem()

        reply = self.fetchers[row].reply()

        if not reply:
            cell.setText(tr('Error'))
            self.display_action(row, Qgis.Warning, 'Temporary not available')

        if reply.error() != QNetworkReply.NoError:
            if reply.error() == QNetworkReply.HostNotFoundError:
                self.display_action(
                    row, Qgis.Warning,
                    'Host can not be found. Is-it an intranet server ?')
            if reply.error() == QNetworkReply.ContentNotFoundError:
                self.display_action(
                    row, Qgis.Critical,
                    'Not a valid Lizmap URL or this version is already not maintained < 3.2'
                )
            else:
                self.display_action(row, Qgis.Critical, reply.errorString())
            cell.setText(tr('Error'))
        else:

            content = self.fetchers[row].contentAsString()
            if not content:
                self.display_action(row, Qgis.Critical,
                                    'Not a valid Lizmap URL')
                return

            try:
                content = json.loads(content)
            except json.JSONDecodeError:
                self.display_action(row, Qgis.Critical, 'Not a JSON document.')
                return

            info = content.get('info')
            if not info:
                self.display_action(row, Qgis.Critical,
                                    'No "info" in the JSON document')
                return

            version = info.get('version')
            if not info:
                self.display_action(row, Qgis.Critical,
                                    'No "version" in the JSON document')
                return

            cell.setText(version)
            self.update_action_version(version, row)

        self.table.setItem(row, 1, cell)
Exemplo n.º 16
0
 def applyConceptToColumn(self, costumURI=False):
     print("test")
     if costumURI:
         if self.costumproperty.text() == "":
             return
         toinsert = self.costumproperty.text()
     else:
         if self.searchResult.count() == 0:
             return
         toinsert = str(self.searchResult.currentItem().data(1))
     if self.bothOptions == True:
         haschanged = False
         if self.currentprefixes != None:
             for prefix in self.currentprefixes:
                 if self.currentprefixes[prefix] in toinsert:
                     toinsert = toinsert.replace(
                         self.currentprefixes[prefix], prefix + ":")
                     haschanged = True
         if haschanged:
             self.table.insertPlainText(toinsert)
         else:
             self.table.insertPlainText("<" + toinsert + ">")
     elif self.interlinkOrEnrich == -1:
         self.table.setText(str(toinsert))
     else:
         if costumURI:
             item = QTableWidgetItem(toinsert)
             item.setText(toinsert)
         else:
             item = QTableWidgetItem(self.searchResult.currentItem().text())
             item.setText(self.searchResult.currentItem().text())
         item.setData(1, toinsert)
         if self.interlinkOrEnrich:
             self.table.setItem(self.currentrow, self.currentcol, item)
         else:
             item2 = QTableWidgetItem()
             item2.setText(self.tripleStoreEdit.currentText())
             item2.setData(
                 0,
                 self.triplestoreconf[self.tripleStoreEdit.currentIndex() +
                                      1]["endpoint"])
             self.table.setItem(self.currentrow, self.currentcol, item)
             self.table.setItem(self.currentrow, (self.currentcol + 1),
                                item2)
     self.close()
Exemplo n.º 17
0
    def _edit_trace_row(self, row, data):
        """Internal function to edit a row."""
        for i, key in enumerate(self.config.layer_config['traces']['items']):
            cell = QTableWidgetItem()

            value = data.get(key)
            if not value:
                cell.setText('')
                cell.setData(Qt.UserRole, '')
                self.traces.setItem(row, i, cell)
                continue

            input_type = self.config.layer_config[key]['type']
            if 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.currentLayer().fields().indexFromName(
                        value)
                    if index >= 0:
                        cell.setIcon(
                            self.layer.currentLayer().fields().iconForField(
                                index))

            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))

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

            self.traces.setItem(row, i, cell)
        self.traces.clearSelection()
Exemplo n.º 18
0
    def _edit_row(self, row, server_url):
        """ Internal function to edit a row. """
        # URL
        cell = QTableWidgetItem()
        cell.setText(server_url)
        cell.setData(Qt.UserRole, server_url)
        self.table.setItem(row, 0, cell)

        # Version
        cell = QTableWidgetItem()
        cell.setText(tr(''))
        cell.setData(Qt.UserRole, None)
        self.table.setItem(row, 1, cell)

        # Action
        cell = QTableWidgetItem()
        cell.setText('')
        cell.setData(Qt.UserRole, '')
        self.table.setItem(row, 2, cell)

        self.table.clearSelection()
        self.fetch(server_url, row)
Exemplo n.º 19
0
 def readMapping(self,filename):
     if self.dlg.interlinkTable.rowCount()!=0:
         tree = ET.parse(filename)
         root = tree.getroot()
         filedata=root.find('file')[0]
         self.dlg.interlinkNameSpace.setText(filedata.get("namespace"))
         self.dlg.interlinkOwlClassInput.setText(filedata.get("class"))  
         for neighbor in root.iter('column'):
             name=neighbor.get("name")
             proptype=neighbor.get("prop")
             propiri=neighbor.get("propiri")
             concept=neighbor.get("concept")
             query=neighbor.get("query")
             triplestoreurl=neighbor.get("triplestoreurl")
             valuemappings={}
             for vmap in neighbor.findall("valuemapping"):
                 valuemappings[vmap.get("from")]=vmap.get("to")
             for row in range(self.dlg.interlinkTable.rowCount()):
                 columnname=self.dlg.interlinkTable.item(row,3).text()
                 if columnname==name:
                     if propiri!=None:
                         item=QTableWidgetItem(propiri)
                         item.setText(propiri)
                         item.setData(1,propiri)
                         self.dlg.interlinkTable.setItem(row,4,item)
                     if proptype!=None:
                         comboboxx=self.dlg.interlinkTable.cellWidget(row,5)
                         if proptype=="annotation":
                             comboboxx.setCurrentIndex(comboboxx.findText("AnnotationProperty", QtCore.Qt.MatchFixedString))
                         elif proptype=="obj":
                             comboboxx.setCurrentIndex(comboboxx.findText("ObjectProperty", QtCore.Qt.MatchFixedString))
                         elif proptype=="data":
                             comboboxx.setCurrentIndex(comboboxx.findText("DataProperty", QtCore.Qt.MatchFixedString))
                         elif proptype=="subclass":
                             comboboxx.setCurrentIndex(comboboxx.findText("SubClass", QtCore.Qt.MatchFixedString))
                         else:
                             comboboxx.setCurrentIndex(comboboxx.findText("Automatic", QtCore.Qt.MatchFixedString))
                     if concept!=None:
                         item=QTableWidgetItem(concept)
                         item.setText(concept)
                         item.setData(1,concept)
                         self.dlg.interlinkTable.setItem(row,6,item)
                     if valuemappings!={} and valuemappings!=None:
                         item=QTableWidgetItem("ValueMap{}")
                         item.setText("ValueMap{}")
                         item.setData(1,valuemappings)
                         if query!=None:
                             item.setData(2,query)
                             item.setData(3,triplestoreurl)                                
                         self.dlg.interlinkTable.setItem(row,7,item)
                     elif query!=None:
                         item=QTableWidgetItem("ValueMap{}")
                         item.setText("ValueMap{}")
                         item.setData(2,query)
                         item.setData(3,triplestoreurl)
                         if valuemappings!={} and valuemappings!=None:
                             item.setData(1,valuemappings)                                
                         self.dlg.interlinkTable.setItem(row,7,item)                            
     else:
         msgBox=QMessageBox()
         msgBox.setText("Please first load a dataset to enrich before loading a mapping file")
         msgBox.exec()
Exemplo n.º 20
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()
Exemplo n.º 21
0
    def configureDialog(self,
                        p_layertype,
                        p_wkbtype,
                        p_Multitype=False,
                        p_Z=False,
                        p_M=False,
                        p_EditMode=False,
                        p_Canvas=None):
        """ Init dialog controls """

        self.layertype = p_layertype
        self.wkbtype = p_wkbtype
        self.has_Z = p_Z
        self.has_M = p_M
        self.isMultiType = p_Multitype
        self.isEditMode = p_EditMode
        self.mapCanvas = p_Canvas
        self.projectCrsId = self.mapCanvas.mapSettings().destinationCrs(
        ).srsid()
        self.highLighter = HighlightFeature(
            self.mapCanvas, self.layertype == QgsWkbTypes.PointGeometry,
            self.layertype == QgsWkbTypes.PolygonGeometry, self.projectCrsId)
        self.valueChecker = ValueChecker(self.twPoints, self.layertype)

        # Hide working with parts for any point geometry and simple line geometry
        if self.layertype == QgsWkbTypes.PointGeometry or \
                (self.layertype == QgsWkbTypes.LineGeometry and not self.isMultiType):
            self.partButtonsFrame.hide()
            self.partsFrame.hide()
            self.gridMainLayout.setHorizontalSpacing(0)

        # Else activate multipart controls
        else:
            self.partButtonsFrame.show()
            self.partsFrame.show()
            self.gridMainLayout.setHorizontalSpacing(3)

            # Set enabled state Add ring button only for polygons
            self.toolButtonAddRing.setEnabled(
                self.layertype == QgsWkbTypes.PolygonGeometry)

            # Disable add parts buttons for not multipolygone (only add ring enabled)
            self.toolButtonAddPart.setEnabled(self.isMultiType)

            model = self.listParts.model()
            model.blockSignals(True)
            model.insertRows(0, 1)
            model.setData(model.index(0), '1', QtCore.Qt.EditRole)
            model.blockSignals(False)

            self.__contursCount = 1
            self.prev_row = 0

        if self.has_Z and self.has_M:
            tableColumns = 4
            headerLabels = ['X', 'Y', 'Z', 'M']
        elif self.has_Z != self.has_M:
            tableColumns = 3
            if self.has_Z:
                headerLabels = ['X', 'Y', 'Z']
            else:
                headerLabels = ['X', 'Y', 'M']
        else:
            tableColumns = 2
            headerLabels = ['X', 'Y']

        modelColumns = self.twPoints.model().columnCount()

        if tableColumns > modelColumns:
            self.twPoints.model().insertColumns(2, tableColumns - modelColumns)
        elif tableColumns < modelColumns:
            self.twPoints.model().removeColumns(2, modelColumns - tableColumns)

        for i in range(len(headerLabels)):
            if self.twPoints.horizontalHeaderItem(i) is not None:
                self.twPoints.horizontalHeaderItem(i).setText(headerLabels[i])
            else:
                item = QTableWidgetItem()
                item.setText(headerLabels[i])
                self.twPoints.setHorizontalHeaderItem(i, item)

        # Resize grid. Set column's width equal. Resize the section to fill the available space.
        for i in range(self.twPoints.columnCount()):
            self.twPoints.setColumnWidth(
                i,
                self.twPoints.width() / self.twPoints.columnCount())
            self.twPoints.horizontalHeader().setSectionResizeMode(
                i, QHeaderView.Stretch)

        # Disable OK button. Wait for entering valid coordinates
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

        # Disable choose CRS button while not selected rb_ChooseCrs
        self.l_OtherCrsName.setEnabled(self.rb_OtherCrs.isChecked())
        self.pb_OtherCrs.setEnabled(self.rb_OtherCrs.isChecked())

        settings = QSettings()

        rb_checked = settings.value("/Plugin-NumericalDigitize/Projection",
                                    "LayerCrs",
                                    type=str)
        if rb_checked == "ProjectCrs":
            self.featureCrsId = self.projectCrsId
            self.rb_ProjectCrs.setChecked(True)
        elif rb_checked == "OtherCrs":
            self.otherCrsId = settings.value(
                "/Plugin-NumericalDigitize/OtherCrsId", -1, type=int)
            self.featureCrsId = self.otherCrsId
            self.__displayAuthid()
            self.rb_OtherCrs.setChecked(True)
        else:
            self.featureCrsId = self.mapCanvas.currentLayer().crs().srsid()
            self.rb_LayerCrs.setChecked(True)

        self.selectedCRS.emit(self.featureCrsId)
Exemplo n.º 22
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()