def testRectangle(self):
        rect = QgsReferencedRectangle(QgsRectangle(0.0, 1.0, 20.0, 10.0), QgsCoordinateReferenceSystem('epsg:3111'))
        self.assertEqual(rect.xMinimum(), 0.0)
        self.assertEqual(rect.yMinimum(), 1.0)
        self.assertEqual(rect.xMaximum(), 20.0)
        self.assertEqual(rect.yMaximum(), 10.0)
        self.assertEqual(rect.crs().authid(), 'EPSG:3111')

        rect.setCrs(QgsCoordinateReferenceSystem('epsg:28356'))
        self.assertEqual(rect.crs().authid(), 'EPSG:28356')

        # in variant
        v = QVariant(QgsReferencedRectangle(QgsRectangle(1.0, 2.0, 3.0, 4.0), QgsCoordinateReferenceSystem('epsg:3111')))
        self.assertEqual(v.value().xMinimum(), 1.0)
        self.assertEqual(v.value().yMinimum(), 2.0)
        self.assertEqual(v.value().xMaximum(), 3.0)
        self.assertEqual(v.value().yMaximum(), 4.0)
        self.assertEqual(v.value().crs().authid(), 'EPSG:3111')

        # to rectangle
        r = QgsRectangle(rect)
        self.assertEqual(r.xMinimum(), 0.0)
        self.assertEqual(r.yMinimum(), 1.0)
        self.assertEqual(r.xMaximum(), 20.0)
        self.assertEqual(r.yMaximum(), 10.0)

        # test that QgsReferencedRectangle IS a QgsRectangle
        r2 = QgsRectangle(5, 6, 30, 40)
        r2.combineExtentWith(rect)
        self.assertEqual(r2.xMinimum(), 0.0)
        self.assertEqual(r2.yMinimum(), 1.0)
        self.assertEqual(r2.xMaximum(), 30.0)
        self.assertEqual(r2.yMaximum(), 40.0)
    def test_make_features_compatible_attributes(self):
        """Test corner cases for attributes"""

        # Test feature without attributes
        fields = QgsFields()
        fields.append(QgsField('int_f', QVariant.Int))
        fields.append(QgsField('str_f', QVariant.String))
        layer = QgsMemoryProviderUtils.createMemoryLayer(
            'mkfca_layer', fields, QgsWkbTypes.Point,
            QgsCoordinateReferenceSystem(4326))
        self.assertTrue(layer.isValid())
        f1 = QgsFeature(layer.fields())
        f1['int_f'] = 1
        f1['str_f'] = 'str'
        f1.setGeometry(QgsGeometry.fromWkt('Point(9 45)'))
        new_features = QgsVectorLayerUtils.makeFeaturesCompatible([f1], layer)
        self.assertEqual(new_features[0].attributes(), f1.attributes())
        self.assertTrue(new_features[0].geometry().asWkt(),
                        f1.geometry().asWkt())

        # Test pad with 0 with fields
        f1.setAttributes([])
        new_features = QgsVectorLayerUtils.makeFeaturesCompatible([f1], layer)
        self.assertEqual(len(new_features[0].attributes()), 2)
        self.assertEqual(new_features[0].attributes()[0], QVariant())
        self.assertEqual(new_features[0].attributes()[1], QVariant())

        # Test pad with 0 without fields
        f1 = QgsFeature()
        f1.setGeometry(QgsGeometry.fromWkt('Point(9 45)'))
        new_features = QgsVectorLayerUtils.makeFeaturesCompatible([f1], layer)
        self.assertEqual(len(new_features[0].attributes()), 2)
        self.assertEqual(new_features[0].attributes()[0], QVariant())
        self.assertEqual(new_features[0].attributes()[1], QVariant())

        # Test drop extra attrs
        f1 = QgsFeature(layer.fields())
        f1.setAttributes([1, 'foo', 'extra'])
        f1.setGeometry(QgsGeometry.fromWkt('Point(9 45)'))
        new_features = QgsVectorLayerUtils.makeFeaturesCompatible([f1], layer)
        self.assertEqual(len(new_features[0].attributes()), 2)
        self.assertEqual(new_features[0].attributes()[0], 1)
        self.assertEqual(new_features[0].attributes()[1], 'foo')
    def testPoint(self):
        point = QgsReferencedPointXY(QgsPointXY(1.0, 2.0), QgsCoordinateReferenceSystem('epsg:3111'))
        self.assertEqual(point.x(), 1.0)
        self.assertEqual(point.y(), 2.0)
        self.assertEqual(point.crs().authid(), 'EPSG:3111')

        point.setCrs(QgsCoordinateReferenceSystem('epsg:28356'))
        self.assertEqual(point.crs().authid(), 'EPSG:28356')

        # in variant
        v = QVariant(QgsReferencedPointXY(QgsPointXY(3.0, 4.0), QgsCoordinateReferenceSystem('epsg:3111')))
        self.assertEqual(v.value().x(), 3.0)
        self.assertEqual(v.value().y(), 4.0)
        self.assertEqual(v.value().crs().authid(), 'EPSG:3111')

        # to QgsPointXY
        p = QgsPointXY(point)
        self.assertEqual(p.x(), 1.0)
        self.assertEqual(p.y(), 2.0)
    def testPoint(self):
        point = QgsReferencedPointXY(QgsPointXY(1.0, 2.0), QgsCoordinateReferenceSystem('epsg:3111'))
        self.assertEqual(point.x(), 1.0)
        self.assertEqual(point.y(), 2.0)
        self.assertEqual(point.crs().authid(), 'EPSG:3111')

        point.setCrs(QgsCoordinateReferenceSystem('epsg:28356'))
        self.assertEqual(point.crs().authid(), 'EPSG:28356')

        # in variant
        v = QVariant(QgsReferencedPointXY(QgsPointXY(3.0, 4.0), QgsCoordinateReferenceSystem('epsg:3111')))
        self.assertEqual(v.value().x(), 3.0)
        self.assertEqual(v.value().y(), 4.0)
        self.assertEqual(v.value().crs().authid(), 'EPSG:3111')

        # to QgsPointXY
        p = QgsPointXY(point)
        self.assertEqual(p.x(), 1.0)
        self.assertEqual(p.y(), 2.0)
示例#5
0
 def data(self, index, role=Qt.DisplayRole):
     # super().data(index, role=Qt.DisplayRole)
     if not index.isValid() or not (0 <= index.row() < self.rowCount() \
         and 0 <= index.column() < self.columnCount()):
         return QVariant()
     row = self._dataframe.index[index.row()]
     col = self._dataframe.columns[index.column()]
     dt = self._dataframe[col].dtype
     try:
         val = self._dataframe.iloc[row][col]
     except:
         return QVariant()
     if role == Qt.TextAlignmentRole:
         return Qt.AlignVCenter + Qt.AlignHCenter
     elif role == Qt.DisplayRole:
         if pd.isnull(val) or val != val:
             return '-'
         if index.column() == 2:
             return str(val)
         if isinstance(val, (float, np.float32)) and index.column() >= 3:
             return "%.2f" % val
         return str(val)
     elif role == Qt.BackgroundRole:
         if index.column() == 0 or index.column() == 1:
             return QVariant()
         elif index.column() == 2:
             return QColor('#404040')
         elif (isinstance(val, float)
               or isinstance(val, np.float32)) and index.column() >= 3:
             if not pd.isnull(val) or not val:
                 mod_val = int(round(val * 10, 0))
                 return QColor(ADfModel.COLORS[mod_val])
             else:
                 return QVariant()
     elif role == Qt.ForegroundRole:
         if index.column() == 2:
             return QColor('#ffffff')
     elif role == DataFrameModel.ValueRole:
         return val
     if role == DataFrameModel.DtypeRole:
         return dt
     return QVariant()
    def checkModelValue(self, i, j):
        model = self.tableViewWidget.model()

        if i > model.rowCount() or i < 0:
            return CellValue.ValueNone
        if j > model.columnCount() or j < 0:
            return CellValue.ValueNone

        return self.checkValue(
            QVariant(model.data(model.index(i, j, QModelIndex()),
                                Qt.EditRole)))
示例#7
0
 def initAlgorithm(self, config=None):
     self.addParameter(
         QgsProcessingParameterVectorLayer(self.initial_points,
                                           self.tr("Initial Point(s)"),
                                           [QgsProcessing.TypeVectorPoint],
                                           None, False))
     self.addParameter(
         QgsProcessingParameterNumber(self.analysed_radius,
                                      self.tr("Analysed Radius"),
                                      QgsProcessingParameterNumber.Double,
                                      QVariant(800)))
     self.addParameter(
         QgsProcessingParameterNumber(self.aggregation_scale,
                                      self.tr("Aggregation Scale"),
                                      QgsProcessingParameterNumber.Double,
                                      QVariant(1000)))
     self.addParameter(
         QgsProcessingParameterVectorLayer(
             self.street_network, self.tr("Street Network"),
             [QgsProcessing.TypeVectorAnyGeometry], None, False))
     self.addParameter(
         QgsProcessingParameterVectorLayer(self.intersections,
                                           self.tr("Intersections"),
                                           [QgsProcessing.TypeVectorPoint],
                                           None, False))
     self.addParameter(
         QgsProcessingParameterVectorLayer(
             self.osm_land, self.tr("OSM Land Data"),
             [QgsProcessing.TypeVectorPolygon], None, False))
     self.addParameter(
         QgsProcessingParameterFeatureSource(
             self.sample_input, self.tr("Sample"),
             [QgsProcessing.TypeVectorAnyGeometry], None, False))
     self.addParameter(
         QgsProcessingParameterNumber(self.target_crs,
                                      self.tr("Target CRS"),
                                      QgsProcessingParameterNumber.Double,
                                      QVariant(1000)))
     self.addParameter(
         QgsProcessingParameterFeatureSink(self.sample_output,
                                           self.tr("Walkability")))
示例#8
0
 def data(self, index, role):
     val = super().data(index, role)
     if role == Qt.DisplayRole:
         name = self.get_text(index.row(), self.col_name)
         token = self.get_text(index.row(), self.col_token)
         if token:
             msg = self.named_token.format(
                 name=name,
                 token=token) if name else self.nonamed_token.format(
                     token=token)
             return QVariant(msg)
     return val
示例#9
0
 def headerData(self, section: int, orientation: Qt.Orientation, role: int = Qt.DisplayRole):
     if role == Qt.DisplayRole:
         if orientation == Qt.Horizontal:
             if self.col_names:
                 try:
                     return self.col_names[section]  # type: ignore
                 except:
                     pass
             return self._dataframe.columns[section]
         else:
             return str(self._dataframe.index[section])
     return QVariant()
    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        self.addParameter(
            QgsProcessingParameterVectorLayer(self.INPUT_POINTS,
                                              self.tr('Point layer'),
                                              [QgsProcessing.TypeVectorPoint]))

        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.INPUT_ZONES, self.tr('Zones layer'),
                [QgsProcessing.TypeVectorPolygon]))

        self.addParameter(
            QgsProcessingParameterField(self.FIELD_ID,
                                        self.tr("Zones identifiant"),
                                        QVariant(), self.INPUT_ZONES))

        self.addParameter(
            QgsProcessingParameterBoolean(
                self.BOOLEAN,
                self.tr('Index calculation for all numeric fields')))

        self.addParameter(
            QgsProcessingParameterField(
                self.FIELD,
                self.tr("Fields for which the zoning index is calculated"),
                QVariant(),
                self.INPUT_POINTS,
                type=QgsProcessingParameterField.Numeric))

        self.addParameter(
            QgsProcessingParameterFileDestination(
                self.OUTPUT,
                self.tr('File'),
                '.csv',
            ))
    def find_duplicate_value(self, source_value, source_field_type,
                             target_value_dict, target_field_type):
        """
        Check if source_value is in target layer. First, as is, and if necessary as a converted value.

        :param source_value: single value from the source layer
        :param source_field_type: QVariant.Type
        :param target_value_dict: dict of unique values in the target layer. We only use keys in this function.
        :param target_field_type: QVariant.Type
        :return: Whether the source_value is duplicated in the target layer and, if so, also the target value
        """
        # Direct comparison
        if source_field_type == target_field_type:
            if source_value in target_value_dict:
                return True, source_value
            else:
                return False, None

        # We first need to convert types before comparing...
        qvariant_value = QVariant(source_value)
        res_can_convert = qvariant_value.canConvert(target_field_type)
        if res_can_convert:
            res_convert = qvariant_value.convert(target_field_type)
            if res_convert:
                if qvariant_value.value() in target_value_dict:
                    return True, qvariant_value.value()

        return False, None
示例#12
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)
示例#13
0
 def _toStrResultSet(self, res):
     newres = []
     for rec in res:
         newrec = []
         for col in rec:
             if type(col) == type(QVariant(None)):
                 if (str(col) == 'NULL'):
                     col = None
                 else:
                     col = str(col) # force to string
             newrec.append(col)
         newres.append(newrec)
     return newres
示例#14
0
    def test_model(self):
        """Test the model"""

        md = QgsProviderRegistry.instance().providerMetadata('postgres')
        conn = md.createConnection(self.uri, {})
        res = conn.execSql('SELECT generate_series(1, 1000)')
        model = QgsQueryResultModel(res)
        self.assertEqual(model.rowCount(model.index(-1, -1)), 0)

        while model.rowCount(model.index(-1, -1)) < 1000:
            QCoreApplication.processEvents()

        self.assertEqual(model.columnCount(model.index(-1, -1)), 1)
        self.assertEqual(model.rowCount(model.index(-1, -1)), 1000)
        self.assertEqual(model.data(model.index(999, 0), Qt.DisplayRole), 1000)

        # Test data
        for i in range(1000):
            self.assertEqual(model.data(model.index(i, 0), Qt.DisplayRole), i + 1)

        self.assertEqual(model.data(model.index(1000, 0), Qt.DisplayRole), QVariant())
        self.assertEqual(model.data(model.index(1, 1), Qt.DisplayRole), QVariant())
示例#15
0
    def test_overwriteDefaultValues(self):
        """Test that unchanged values are not stored"""
        self.globalsettings.setValue('a_value_with_default', 'a value')
        self.globalsettings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Now, set them with the same current value
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        # Check
        pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat)
        self.assertFalse('a_value_with_default' in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' in pure_settings.allKeys())

        # Set a changed value
        self.settings.setValue('a_value_with_default', 'a new value')
        self.settings.setValue('an_invalid_value', 'valid value')

        # Check
        self.assertTrue('a_value_with_default' in pure_settings.allKeys())
        self.assertTrue('an_invalid_value' in pure_settings.allKeys())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a new value')
        self.assertEqual(self.settings.value('an_invalid_value'), 'valid value')

        # Re-set to original values
        self.settings.setValue('a_value_with_default', 'a value')
        self.settings.setValue('an_invalid_value', QVariant())

        self.assertEqual(self.settings.value('a_value_with_default'), 'a value')
        self.assertEqual(self.settings.value('an_invalid_value'), QVariant())

        # Check if they are gone
        pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat)
        self.assertFalse('a_value_with_default' not in pure_settings.allKeys())
        self.assertFalse('an_invalid_value' not in pure_settings.allKeys())
示例#16
0
    def data(self, index, role=Qt.DisplayRole):
        field = self._mapping[index.row()]
        column_def = self.columns[index.column()]

        if role == Qt.DisplayRole:
            value = field[column_def['name']] if column_def[
                'name'] in field else QVariant()
            if column_def['type'] == QVariant.Type:
                if value == QVariant.Invalid:
                    return ''
                return self.fieldTypes[value]
            elif column_def['name'] == 'constraints' and value:
                return self.tr("Constraints active")

            return value

        if role == Qt.EditRole:
            return field[column_def['name']]

        if role == Qt.TextAlignmentRole:
            if column_def['type'] in [QVariant.Int]:
                hAlign = Qt.AlignRight
            else:
                hAlign = Qt.AlignLeft
            return hAlign + Qt.AlignVCenter

        if role == Qt.BackgroundRole:
            return QBrush(
                QColor(255, 224, 178)
            ) if 'constraints' in field and field['constraints'] else QVariant(
            )

        if role == Qt.ToolTipRole:
            if column_def['name'] == 'constraints' and 'constraints' in field:
                return "<br>".join([
                    self.constraints[constraint]
                    for constraint in field['constraints']
                ])
示例#17
0
文件: qtmodels.py 项目: gltn/stdm
    def data(self, index, role):

        indexData = self.persondata[index.row()][index.column()]

        if not index.isValid():
            return QVariant()

        elif role == Qt.DisplayRole:
            col = index.column()

            # Specify formatters for columns whose values are foreign keys
            if col == 5:
                # Gender formatter
                return self._genderFormatter.setDisplay(indexData)

            elif col == 6:
                # Current age calculation
                return self._ageFormatter.setDisplay(indexData)

            elif col == 7:
                return self._mStatFormatter.setDisplay(indexData)

            else:
                return QVariant(indexData)

        # For columns representing foreign keys then we need to pass the integer value to the editor
        elif role == Qt.EditRole:
            # Create QDate from Python date then pass it to QVariant constructor where applicable
            if index.column() == 6:

                if isinstance(indexData, QVariant):
                    return QVariant(indexData)
                else:
                    return QVariant(QDate(indexData))

            else:
                return QVariant(indexData)

        elif role == Qt.BackgroundRole:
            if index.row() % 2 == 0:
                # Orange
                return QVariant(ALT_COLOR_EVEN)
            else:
                # Blue
                return QVariant(ALT_COLOR_ODD)

        else:
            return QVariant()
示例#18
0
    def test_value_nulls(self):
        """Test value NULL and None are not passed through the type compatibility check"""

        feature = self._feature_factory({
            'text_nullable': None,
        }, 'point( 9 45 )')
        errors = feature_validator(feature, self.validator_project_test)
        self.assertFalse('text_nullable' in errors)

        feature = self._feature_factory({
            'text_nullable': QVariant(),
        }, 'point( 9 45 )')
        errors = feature_validator(feature, self.validator_project_test)
        self.assertFalse('text_nullable' in errors)
示例#19
0
    def testRectangle(self):
        rect = QgsReferencedRectangle(
            QgsRectangle(0.0, 1.0, 20.0, 10.0),
            QgsCoordinateReferenceSystem('epsg:3111'))
        self.assertEqual(rect.xMinimum(), 0.0)
        self.assertEqual(rect.yMinimum(), 1.0)
        self.assertEqual(rect.xMaximum(), 20.0)
        self.assertEqual(rect.yMaximum(), 10.0)
        self.assertEqual(rect.crs().authid(), 'EPSG:3111')

        rect.setCrs(QgsCoordinateReferenceSystem('epsg:28356'))
        self.assertEqual(rect.crs().authid(), 'EPSG:28356')

        # in variant
        v = QVariant(
            QgsReferencedRectangle(QgsRectangle(1.0, 2.0, 3.0, 4.0),
                                   QgsCoordinateReferenceSystem('epsg:3111')))
        self.assertEqual(v.value().xMinimum(), 1.0)
        self.assertEqual(v.value().yMinimum(), 2.0)
        self.assertEqual(v.value().xMaximum(), 3.0)
        self.assertEqual(v.value().yMaximum(), 4.0)
        self.assertEqual(v.value().crs().authid(), 'EPSG:3111')

        # to rectangle
        r = QgsRectangle(rect)
        self.assertEqual(r.xMinimum(), 0.0)
        self.assertEqual(r.yMinimum(), 1.0)
        self.assertEqual(r.xMaximum(), 20.0)
        self.assertEqual(r.yMaximum(), 10.0)

        # test that QgsReferencedRectangle IS a QgsRectangle
        r2 = QgsRectangle(5, 6, 30, 40)
        r2.combineExtentWith(rect)
        self.assertEqual(r2.xMinimum(), 0.0)
        self.assertEqual(r2.yMinimum(), 1.0)
        self.assertEqual(r2.xMaximum(), 30.0)
        self.assertEqual(r2.yMaximum(), 40.0)
示例#20
0
 def data(self, index, role=Qt.DisplayRole):
     if not index.isValid() or not (0 <= index.row() < self.rowCount() \
         and 0 <= index.column() < self.columnCount()):
         return QVariant()
     row = self._dataframe.index[index.row()]
     col = self._dataframe.columns[index.column()]
     dt = self._dataframe[col].dtype
     val = self._dataframe.iloc[row][col]
     if role == Qt.DisplayRole:
         if index.column() == 0:
             return QVariant()
         else:
             return str(val)
     elif role == Qt.FontRole:
         font = QFont()
         font.setPointSize(11)
         return font
     elif role == Qt.ForegroundRole:
         if index.row() == self.tv.currentIndex().row():
             return QColor(Qt.white)
         else:
             return QColor(Qt.black)
     elif role == Qt.BackgroundRole:
         if index.row() == self.tv.currentIndex().row():
             gradient = QLinearGradient(0, 0, 66, 0)
             gradient.setColorAt(0, QColor(0, 0, 0, 128))
             gradient.setColorAt(1, QColor(0, 0, 0, 0))
             if index.column() == 0:
                 return QColor(0, 0, 0, 128)
             else:
                 return QBrush(gradient)
     if role == ValueRole:
         return val
     if role == DataFrameModel.DtypeRole:
         return dt
     return QVariant()
示例#21
0
    def _set_add_edit_user_field_choices(self):
        """
        Set choices for add_user_field select and edit_user_field select
        """

        touse = []
        fields = self.layer.qgis_layer.fields()

        for f in fields:
            type = QVariant.typeToName(f.type()).upper()
            if type == 'QSTRING':  # and f.length() > 200:
                touse.append(f.name())

        self.fields['edit_user_field'].choices = \
            self.fields['add_user_field'].choices = [(None, '--------')] + [(f, f) for f in touse]
    def initAlgorithm(self, config=None):
        local_timezone = time.timezone if (time.localtime().tm_isdst
                                           == 0) else time.altzone
        local_timezone /= -3600  # gets the time zone offset of the local machine to use a default

        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT_TRAJECTORIES, self.tr(self.INPUT_TRAJECTORIES),
                [QgsProcessing.TypeVectorLine]))
        self.addParameter(
            QgsProcessingParameterField(self.WEIGHT_FIELD,
                                        self.tr(self.WEIGHT_FIELD), 'Weight',
                                        self.INPUT_TRAJECTORIES,
                                        QgsProcessingParameterField.Numeric,
                                        False, True))
        self.addParameter(
            QgsProcessingParameterBoolean(self.USE_WEIGHT_FIELD,
                                          self.tr(self.USE_WEIGHT_FIELD),
                                          QVariant(False)))
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT_CELL_CENTERS, self.tr(self.INPUT_CELL_CENTERS),
                [QgsProcessing.TypeVectorPoint]))
        self.addParameter(
            QgsProcessingParameterFeatureSink(self.OUTPUT_FLOWLINES,
                                              self.tr(self.OUTPUT_FLOWLINES),
                                              QgsProcessing.TypeVectorLine))
        self.addParameter(
            QgsProcessingParameterFeatureSink(self.OUTPUT_CELL_COUNTS,
                                              self.tr(self.OUTPUT_CELL_COUNTS),
                                              QgsProcessing.TypeVectorPoint))
        self.addParameter(
            QgsProcessingParameterNumber(self.TIMEZONE, self.tr(self.TIMEZONE),
                                         QgsProcessingParameterNumber.Integer,
                                         QVariant(local_timezone), False, -12,
                                         12))
示例#23
0
def is_ors_compatible(layer):
    """Check layer ORS compatibility"""

    if layer.type() != QgsMapLayerType.VectorLayer or layer.readOnly(
    ) or layer.geometryType() != QgsWkbTypes.PolygonGeometry:
        return False
    fields = layer.fields()
    for field_name, field_type in ORS_REQUIRED_LAYER_FIELDS.items():
        # Shapefile attributes max length is 10
        if layer.publicSource().endswith('.shp'):
            field_name = field_name[:10]
        if fields.lookupField(field_name) < 0 or not QVariant(
                fields.field(fields.lookupField(
                    field_name)).type()).canConvert(field_type):
            return False
    return True
示例#24
0
    def isFloat(value):
        q_value = QVariant(value)

        if q_value.isNull():
            return False
        if q_value.convert(QMetaType.QString):
            if str(q_value.value()) == '':
                return False
        if q_value.convert(QMetaType.Float):
            if isnan(float(q_value.value())):
                return False
            else:
                return True
        else:
            return False
示例#25
0
    def testSetSourceFields(self):
        """Test that changing source fields also empty expressions are updated"""

        model = QgsFieldMappingModel(self.source_fields, self.destination_fields)
        self.assertEqual(model.data(model.index(2, 0), Qt.DisplayRole), QVariant())
        self.assertEqual(model.data(model.index(2, 1), Qt.DisplayRole), 'destination_field3')

        f = QgsField('source_field3', QVariant.String)
        fields = self.source_fields
        fields.append(f)
        model.setSourceFields(fields)
        self.assertEqual(model.data(model.index(0, 0), Qt.DisplayRole), '"source_field2"')
        self.assertEqual(model.data(model.index(0, 1), Qt.DisplayRole), 'destination_field1')
        self.assertEqual(model.data(model.index(1, 0), Qt.DisplayRole), '"source_field1"')
        self.assertEqual(model.data(model.index(1, 1), Qt.DisplayRole), 'destination_field2')
        self.assertEqual(model.data(model.index(2, 0), Qt.DisplayRole), '"source_field3"')
        self.assertEqual(model.data(model.index(2, 1), Qt.DisplayRole), 'destination_field3')
    def getSourceFeatureAttributesWithInfo(self, sourceFeature):
        data = []
        for index, field in enumerate(self.sourceLayerFields):
            if field.name(
            ) != 'id' and self.yleiskaavaUtils.getStringTypeForFeatureField(
                    field) != 'uuid':
                data.append({
                    "name":
                    field.name(),
                    "type":
                    self.yleiskaavaUtils.getStringTypeForFeatureField(field),
                    "value":
                    QVariant(sourceFeature[field.name()])
                })

                # QgsMessageLog.logMessage("getSourceFeatureAttributesWithInfo - name: " + field.name() + ", type: " + str(self.yleiskaavaUtils.getStringTypeForFeatureField(field)) + ", value: " + str(QVariant(sourceFeature[field.name()]).value()), 'Yleiskaava-työkalu', Qgis.Info)

        return data
    def refreshTable(self, part_num):
        # Clear coord's table
        if -1 < part_num < len(self.coords_matrix):
            model = self.twPoints.model()
            coordslist = self.coords_matrix[part_num][1]

            model.removeRows(0, model.rowCount())
            model.insertRows(0, len(self.coords_matrix[part_num][1]) + 1)

            model.blockSignals(True)
            for i in range(len(coordslist)):
                for j in range(model.columnCount()):
                    model.setData(model.createIndex(i, j),
                                  QVariant(str(coordslist[i][j])))
            model.blockSignals(False)
            model.dataChanged.emit(
                model.createIndex(0, 0),
                model.createIndex(model.rowCount() - 1,
                                  model.columnCount() - 1))
示例#28
0
    def setValue(self, value):
        if type(value) != dict:
            return
        destinationFields = QgsFields()
        expressions = {}
        for field_def in value:
            f = QgsField(
                field_def.get('name'), field_def.get('type', QVariant.Invalid),
                field_def.get(
                    QVariant.typeToName(field_def.get('type',
                                                      QVariant.Invalid))),
                field_def.get('length', 0), field_def.get('precision', 0))
            try:
                expressions[f.name()] = field_def['expressions']
            except AttributeError:
                pass
            destinationFields.append(f)

        if len(destinationFields):
            self.fieldsView.setDestinationFields(destinationFields,
                                                 expressions)
    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        self.addParameter(
            QgsProcessingParameterVectorLayer(self.INPUT,
                                              self.tr('Point layer'),
                                              [QgsProcessing.TypeVectorPoint]))

        self.addParameter(
            QgsProcessingParameterEnum(self.INPUT_METHOD,
                                       self.tr('Interpolation method'), [
                                           'Thiessen', 'Voronoi', 'Delaunay',
                                           'Inverse distance weighting'
                                       ]))

        self.addParameter(
            QgsProcessingParameterField(
                self.FIELD,
                self.tr("Field to interpolate"),
                QVariant(),
                self.INPUT,
                type=QgsProcessingParameterField.Numeric))

        self.addParameter(
            QgsProcessingParameterNumber(
                self.INPUT_PIXEL, self.tr('Grid resolution (in meters)'),
                QgsProcessingParameterNumber.Double, 0.5))

        self.addParameter(
            QgsProcessingParameterNumber(self.INPUT_POWER,
                                         self.tr('IDW power (for IDW method)'),
                                         QgsProcessingParameterNumber.Integer,
                                         2))

        self.addParameter(
            QgsProcessingParameterRasterDestination(
                self.OUTPUT, self.tr('Interpolated raster')))
示例#30
0
 def initAlgorithm(self, config=None):
     self.addParameter(
         QgsProcessingParameterRasterLayer(self.INPUT_RASTER_A,
                                           self.tr("Input Raster A"), None,
                                           False))
     self.addParameter(
         QgsProcessingParameterRasterLayer(self.INPUT_RASTER_B,
                                           self.tr("Input Raster B"), None,
                                           False))
     self.addParameter(
         QgsProcessingParameterNumber(self.INPUT_DOUBLE,
                                      self.tr("Input Double"),
                                      QgsProcessingParameterNumber.Double,
                                      QVariant(1.0)))
     self.addParameter(
         QgsProcessingParameterRasterDestination(self.OUTPUT_RASTER_A,
                                                 self.tr("Output Raster A"),
                                                 None, False))
     self.addParameter(
         QgsProcessingParameterRasterDestination(self.OUTPUT_RASTER_B,
                                                 self.tr("Output Raster B"),
                                                 None, False))
            def addItem():
                if checkListFormValidity():
                    newListWidgetItem = QListWidgetItem()
                    data = {}
                    textList = []
                    for formItem in formItems:
                        if isinstance(formItem, QLineEdit):
                            data[formItem.objectName()] = formItem.text()
                            textList.append(formItem.text())
                        elif isinstance(formItem, QDateTimeEdit):
                            data[formItem.objectName()] = formItem.dateTime().date()
                            textList.append(
                                formItem.dateTime().toString("dd-MM-yyyy")
                                # formItem.dateTime().date().toString()
                            )
                        elif isinstance(formItem, QCheckBox):
                            data[formItem.objectName()] = formItem.isChecked()
                        elif isinstance(formItem, QComboBox):
                            data[formItem.objectName()] = formItem.currentIndex()

                    newListWidgetItem.setData(
                        Qt.UserRole,
                        QVariant(data)
                    )
                    newListWidgetItem.setText(" - ".join(textList))
                    listWidget.addItem(newListWidgetItem)
                    clearDataFromListWidget()   # czyszczenie
                else:
                    if name == 'mapaPodkladowa':
                        utils.showPopup("Wypełnij formularz mapy podkładowej",
                                        'Musisz zdefiniować wartości dla obowiązkowych pól:\n'
                                        '- referencja,\n'
                                        '- data')
                    else:
                        utils.showPopup("Wypełnij formularz",
                                        "Musisz wpisać wartość przed dodaniem")
示例#32
0
    def test_representValueWithDefault(self):
        """
        Check representValue behaves correctly when used on a layer which define default values
        """

        dbname = os.path.join(tempfile.mkdtemp(), 'test.sqlite')
        con = spatialite_connect(dbname, isolation_level=None)
        cur = con.cursor()
        cur.execute("BEGIN")
        sql = """
        CREATE TABLE test_table_default_values (
            id integer primary key autoincrement,
            anumber INTEGER DEFAULT 123
        )
        """
        cur.execute(sql)
        cur.execute("COMMIT")
        con.close()

        vl = QgsVectorLayer(dbname + '|layername=test_table_default_values',
                            'test_table_default_values', 'ogr')
        self.assertTrue(vl.isValid())

        fieldFormatter = QgsFallbackFieldFormatter()

        QLocale.setDefault(QLocale('en'))

        self.assertEqual(
            fieldFormatter.representValue(vl, 1, {}, None,
                                          QVariant(QVariant.Int)), 'NULL')
        self.assertEqual(fieldFormatter.representValue(vl, 1, {}, None, 4),
                         '4')
        self.assertEqual(fieldFormatter.representValue(vl, 1, {}, None, "123"),
                         '123')
        # bad field index
        self.assertEqual(fieldFormatter.representValue(vl, 3, {}, None, 5), "")