def append_row(table, label, data): """Append new row to table widget. :param table: The table that shall have the row added to it. :type table: QTableWidget :param label: Label for the row. :type label: str :param data: custom data associated with label value. :type data: str """ # noinspection PyUnresolvedReferences count = table.rowCount() # noinspection PyUnresolvedReferences table.insertRow(table.rowCount()) items = QTableWidgetItem(label) # see for details of why we follow this pattern # http://stackoverflow.com/questions/9257422/ # how-to-get-the-original-python-data-from-qvariant # Make the value immutable. variant = (data,) # To retrieve it again you would need to do: # value = myVariant.toPyObject()[0] items.setData(Qt.UserRole, variant) # set scenario status (ready or not) into table # noinspection PyUnresolvedReferences table.setItem(count, 0, items) # noinspection PyUnresolvedReferences table.setItem(count, 1, QTableWidgetItem(data['status']))
def showFeatureAttributes(self): conflictItem = self.lastSelectedItem self.oursgeom = None self.theirsgeom = None geoms = (self.oursgeom, self.theirsgeom) self.currentConflictedAttributes = [] attribs = list(conflictItem.origin.keys()) self.attributesTable.setRowCount(len(attribs)) self.conflicted = [] for idx, name in enumerate(attribs): font = QFont() font.setBold(True) font.setWeight(75) item = QTableWidgetItem(name) item.setFont(font) self.attributesTable.setItem(idx, 3, item); self.attributesTable.setItem(idx, 4, ValueItem(None, False)); try: values = (conflictItem.origin[name], conflictItem.local[name], conflictItem.remote[name]) except Exception: #Local has been deleted self._afterSolve(False) self.solveModifyAndDelete(conflictItem.conflict.path, self.REMOTE) return except TypeError: #Remote has been deleted self._afterSolve(False) self.solveModifyAndDelete(conflictItem.conflict.path,self.LOCAL) return try: geom = QgsGeometry.fromWkt(values[0]) except: geom = None if geom is not None: self.theirsgeom = QgsGeometry().fromWkt(values[1]) self.oursgeom = QgsGeometry.fromWkt(values[2]) geoms = (self.oursgeom, self.theirsgeom) ok = values[0] == values[1] or values[1] == values[2] or values[0] == values[2] for i, v in enumerate(values): self.attributesTable.setItem(idx, i, ValueItem(v, not ok, geoms)); if not ok: self.conflicted.append(name) else: if values[0] == values[1]: newvalue = values[2] else: newvalue = values[1] self.attributesTable.setItem(idx, 4, ValueItem(newvalue, False, geoms)); self.attributesTable.resizeRowsToContents() self.attributesTable.horizontalHeader().setMinimumSectionSize(150) self.attributesTable.horizontalHeader().setStretchLastSection(True)
def commitClicked(self): feature = self.listWidget.currentItem().feature geom = None self.attributesTable.setRowCount(len(feature)) for idx, attrname in enumerate(feature): value = feature[attrname] font = QFont() font.setBold(True) font.setWeight(75) item = QTableWidgetItem(attrname) item.setFont(font) self.attributesTable.setItem(idx, 0, item); self.attributesTable.setItem(idx, 1, QTableWidgetItem(str(value))); if geom is None: try: geom = QgsGeometry.fromWkt(value) except: pass self.attributesTable.resizeRowsToContents() self.attributesTable.horizontalHeader().setMinimumSectionSize(150) self.attributesTable.horizontalHeader().setStretchLastSection(True) settings = QSettings() prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') types = ["Point", "LineString", "Polygon"] layers = [] if geom is not None: geomtype = types[int(geom.type())] layer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "temp", "memory") pr = layer.dataProvider() feat = QgsFeature() feat.setGeometry(geom) pr.addFeatures([feat]) layer.updateExtents() layer.selectAll() layer.setExtent(layer.boundingBoxOfSelected()) layer.invertSelection() symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) symbol.setColor(Qt.green) symbol.setAlpha(0.5) if QGis.QGIS_VERSION_INT < 29900: layer.setRendererV2(QgsSingleSymbolRendererV2(symbol)) else: layer.setRenderer(QgsSingleSymbolRenderer(symbol)) self.mapCanvas.setRenderFlag(False) self.mapCanvas.setLayerSet([QgsMapCanvasLayer(layer)]) QgsMapLayerRegistry.instance().addMapLayer(layer, False) self.mapCanvas.setExtent(layer.extent()) self.mapCanvas.setRenderFlag(True) layers.append(layer) else: self.mapCanvas.setLayerSet([]) settings.setValue('/Projections/defaultBehaviour', prjSetting)
def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22)
def __init__(self, value, conflicted, geoms = None): QTableWidgetItem.__init__(self) self.value = value if value is None: s = "" elif isinstance(value, str): s = value else: s = str(value) if conflicted: self.setBackgroundColor(Qt.yellow); self.setText(s) self.setFlags(Qt.ItemIsEnabled)
def __init__(self, value): self.value = value if value is None: s = "" elif isinstance(value, str): s = value else: s = str(value) try: geom = QgsGeometry.fromWkt(value) if geom is not None: s = value.split("(")[0] except: pass QTableWidgetItem.__init__(self, s)
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()
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)
def insertNewRow(self): self.tableWidget.insertRow(self.tableWidget.rowCount()) for i in range(self.tableWidget.columnCount()): editItem = QTableWidgetItem('', 0) if i == 0: editItem.setFlags(self.defFlags | Qt.ItemIsUserCheckable) editItem.setCheckState(Qt.Checked) else: editItem.setFlags(self.defFlags) self.tableWidget.setItem(self.tableWidget.rowCount()-1, i, editItem)
def addCoord(self, lat, lon, label='', data=[]): '''Add a coordinate to the list.''' rowcnt = self.resultsTable.rowCount() if rowcnt >= self.maxResults: return self.resultsTable.blockSignals(True) self.resultsTable.insertRow(rowcnt) item = QTableWidgetItem(str(lat)) item.setData(Qt.UserRole, LatLonItem(lat, lon, label, data)) item.setFlags(item.flags() & ~Qt.ItemIsEditable) self.resultsTable.setItem(rowcnt, 0, item) item = QTableWidgetItem(str(lon)) item.setFlags(item.flags() & ~Qt.ItemIsEditable) self.resultsTable.setItem(rowcnt, 1, item) self.resultsTable.setItem(rowcnt, 2, QTableWidgetItem(label)) if self.numCol > 3 and len(data) > 0: for i in range( min(self.numCol-3, len(data))): self.resultsTable.setItem(rowcnt, i+3, QTableWidgetItem(data[i])) self.resultsTable.blockSignals(False) return(rowcnt)
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
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
def setTableContent(self): self.table.clear() self.table.setColumnCount(2) self.table.setColumnWidth(0, 200) self.table.setColumnWidth(1, 200) self.table.setHorizontalHeaderLabels(["Name", "URL"]) self.table.horizontalHeader().setResizeMode(QHeaderView.Stretch) self.table.setRowCount(len(self.remotes)) for i, name in enumerate(self.remotes): url = self.remotes[name] self.table.setRowHeight(i, 22) item = QTableWidgetItem(name, 0) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.table.setItem(i, 0, item) item = QTableWidgetItem(url, 0) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.table.setItem(i, 1, item) self.table.itemSelectionChanged.connect(self.selectionChanged)
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) item_table.setToolTip( "Total number of samples for this class, this is generated\n" "automatically based on the area proportion by the activated\n" "classes, overall standard error and its standard deviation." ) 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 Dev": for m in range(srs_table["row_count"]): item_table = QTableWidgetItem(srs_table["std_dev"][m]) item_table.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter) item_table.setToolTip( "Set the standard deviation for this class") 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) item_table.setToolTip("Enable/disable this class") 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)
def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22)
def fill_table(self, dict_parcels, types_change_detection): num_rows = 0 for type in types_change_detection: # We didn't use COUNT_KEY because for duplicate parcels the count (t_ids) differs from number of parcels num_rows += len( dict_parcels[type][DICT_KEY_PARCEL_T_PARCEL_NUMBER_F]) self.tbl_changes_all_parcels.clearContents() self.tbl_changes_all_parcels.setRowCount(num_rows) self.tbl_changes_all_parcels.setSortingEnabled(False) row = 0 filter_parcels = None for type in types_change_detection: filter_parcels = dict_parcels[type] if filter_parcels[SOURCE_DB] == COLLECTED_DB_SOURCE: inverse = False else: inverse = True # Take the supplies db as base db base_db = self.utils._supplies_db if inverse else self.utils._db self.compared_parcels_data = self.utils.get_compared_parcels_data( inverse) for parcel_number, parcel_attrs in self.compared_parcels_data.items( ): if filter_parcels and parcel_number in filter_parcels[ DICT_KEY_PARCEL_T_PARCEL_NUMBER_F]: item = QTableWidgetItem( parcel_number) if parcel_number else QTableWidgetItem( QgsApplication.nullRepresentation()) item.setData( Qt.UserRole, { base_db.names.T_ID_F: parcel_attrs[base_db.names.T_ID_F], 'inverse': inverse }) self.tbl_changes_all_parcels.setItem(row, 0, item) status = parcel_attrs[PARCEL_STATUS] status_display = parcel_attrs[PARCEL_STATUS_DISPLAY] if filter_parcels: # If we are on the supplies DB, "new" parcels are "missing" parcels from the collected db perspective if filter_parcels[ SOURCE_DB] == SUPPLIES_DB_SOURCE and parcel_attrs[ PARCEL_STATUS_DISPLAY] == CHANGE_DETECTION_NEW_PARCEL: status_display = CHANGE_DETECTION_MISSING_PARCEL status = CHANGE_DETECTION_MISSING_PARCEL item = QTableWidgetItem(status_display) item.setData( Qt.UserRole, { base_db.names.T_ID_F: parcel_attrs[base_db.names.T_ID_F], 'inverse': inverse }) self.tbl_changes_all_parcels.setItem(row, 1, item) color = STATUS_COLORS[status] self.tbl_changes_all_parcels.item(row, 1).setBackground(color) row += 1 self.tbl_changes_all_parcels.setSortingEnabled(True) # Go for parcel ids and then for plot ids parcel_ids_collected = list() parcel_ids_supplies = list() for type in types_change_detection: filter_parcels = dict_parcels[type] if filter_parcels: if filter_parcels[SOURCE_DB] == COLLECTED_DB_SOURCE: parcel_ids_collected.extend( filter_parcels[self.utils._db.names.T_ID_F]) else: parcel_ids_supplies.extend( filter_parcels[self.utils._supplies_db.names.T_ID_F]) plot_ids_collected = list() if parcel_ids_collected: plot_ids_collected = self.utils.ladm_data.get_plots_related_to_parcels( self.utils._db, parcel_ids_collected, None, # Get QGIS plot ids self.utils._layers[self.utils._db.names.OP_PLOT_T][LAYER], self.utils._layers[self.utils._db.names.COL_UE_BAUNIT_T] [LAYER]) plot_ids_supplies = list() if parcel_ids_supplies: plot_ids_supplies = self.utils.ladm_data.get_plots_related_to_parcels_supplies( self.utils._supplies_db, parcel_ids_supplies, None, # Get QGIS plot ids self.utils._supplies_layers[ self.utils._supplies_db.names.GC_PLOT_T][LAYER]) # Now that we've got plot ids, select them and zoom to them (combining the extent from both plot layers) if plot_ids_collected: self.utils._layers[self.utils._db.names.OP_PLOT_T][ LAYER].selectByIds(plot_ids_collected) if plot_ids_supplies: self.utils._supplies_layers[ self.utils._supplies_db.names.GC_PLOT_T][LAYER].selectByIds( plot_ids_supplies) self.zoom_to_selected_plots()
def readConfiguration(self, filePath=None): if filePath is None: filePath = self.configFilePath # Clear the QTableWidget in case it contains any old data self.tableWidget.clear() self.tableWidget.setRowCount(0) # First set up the TableWidget self.tableWidget.setColumnCount(6) labels = ['Constraint', 'Schema', 'Table', 'Geometry Column', 'Search Distance', 'Columns For Reporting'] self.tableWidget.setHorizontalHeaderLabels(labels) # Read the config config = configparser.ConfigParser() config.read(filePath) i = 0 for section in config.sections(): self.tableWidget.insertRow(i) editItem = QTableWidgetItem(section, 0) editItem.setFlags(self.defFlags | Qt.ItemIsUserCheckable) include = config.get(section, 'include') if include.lower() == 't': editItem.setCheckState(Qt.Checked) else: editItem.setCheckState(Qt.Unchecked) self.tableWidget.setItem(i, 0, editItem) schema = config.get(section, 'schema') editItem = QTableWidgetItem(schema, 0) editItem.setFlags(self.defFlags) self.tableWidget.setItem(i, 1, editItem) table = config.get(section, 'table') editItem = QTableWidgetItem(table, 0) editItem.setFlags(self.defFlags) self.tableWidget.setItem(i, 2, editItem) geom_col = config.get(section, 'geom_column') editItem = QTableWidgetItem(geom_col, 0) editItem.setFlags(self.defFlags) self.tableWidget.setItem(i, 3, editItem) buffer_distance = config.get(section, 'buffer_distance') editItem = QTableWidgetItem(buffer_distance, 0) editItem.setFlags(self.defFlags) self.tableWidget.setItem(i, 4, editItem) columns = config.get(section, 'columns') editItem = QTableWidgetItem(columns, 0) editItem.setFlags(self.defFlags) self.tableWidget.setItem(i, 5, editItem) i += 1 self.tableWidget.resizeColumnsToContents() self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
def reloadProject(self): """ Load all layers from the map layer registry into the table. """ self.unsupportedLayersList = list() self.layersTable.setRowCount(0) self.layersTable.setSortingEnabled(False) for layer in list(self.project.mapLayers().values()): layer_source = LayerSource(layer) if not layer_source.is_supported: self.unsupportedLayersList.append(layer_source) count = self.layersTable.rowCount() self.layersTable.insertRow(count) item = QTableWidgetItem(layer.name()) item.setData(Qt.UserRole, layer_source) item.setData(Qt.EditRole, layer.name()) self.layersTable.setItem(count, 0, item) cbx = QComboBox() for action, description in layer_source.available_actions: cbx.addItem(description) cbx.setItemData(cbx.count() - 1, action) if layer_source.action == action: cbx.setCurrentIndex(cbx.count() - 1) self.layersTable.setCellWidget(count, 1, cbx) self.layersTable.resizeColumnsToContents() self.layersTable.sortByColumn(0, Qt.AscendingOrder) self.layersTable.setSortingEnabled(True) # Load Map Themes for theme in self.project.mapThemeCollection().mapThemes(): self.mapThemeComboBox.addItem(theme) self.layerComboBox.setFilters(QgsMapLayerProxyModel.RasterLayer) self.__project_configuration = ProjectConfiguration(self.project) self.createBaseMapGroupBox.setChecked(self.__project_configuration.create_base_map) if self.__project_configuration.base_map_type == ProjectProperties.BaseMapType.SINGLE_LAYER: self.singleLayerRadioButton.setChecked(True) else: self.mapThemeRadioButton.setChecked(True) self.mapThemeComboBox.setCurrentIndex( self.mapThemeComboBox.findText(self.__project_configuration.base_map_theme)) layer = QgsProject.instance().mapLayer(self.__project_configuration.base_map_layer) self.layerComboBox.setLayer(layer) self.mapUnitsPerPixel.setText(str(self.__project_configuration.base_map_mupp)) self.tileSize.setText(str(self.__project_configuration.base_map_tile_size)) self.onlyOfflineCopyFeaturesInAoi.setChecked(self.__project_configuration.offline_copy_only_aoi) if self.unsupportedLayersList: self.unsupportedLayers.setVisible(True) unsuppoerted_layers_text = '<b>{}</b><br>'.format(self.tr('Warning')) unsuppoerted_layers_text += self.tr("There are unsupported layers in your project. They will not be available on QField.") unsuppoerted_layers_text += '<ul>' for layer in self.unsupportedLayersList: unsuppoerted_layers_text += '<li>' + '<b>' + layer.name + ':</b> ' + layer.warning unsuppoerted_layers_text += '<ul>' self.unsupportedLayers.setText(unsuppoerted_layers_text)
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)
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.ItemIsEnabled) item_table.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter) item_table.setToolTip( "Click to set/change the color of this classification button" ) 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 set/change the pixel color/value from the thematic raster" ) else: item_table = QTableWidgetItem("none") item_table.setForeground(QColor("lightGrey")) item_table.setToolTip( "No thematic raster layer selected, if you want enable the\n" "thematic classes, select first a valid thematic raster file" ) item_h = QTableWidgetItem(h) item_h.setForeground(QColor("lightGrey")) self.tableBtnsConfig.setHorizontalHeaderItem(2, item_h) item_table.setFlags(Qt.ItemIsEnabled) 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())
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())
def loadLayerForEnrichment(self): layers = QgsProject.instance().layerTreeRoot().children() selectedLayerIndex = self.chooseLayerEnrich.currentIndex() if len(layers) == 0: return layer = layers[selectedLayerIndex].layer() self.enrichTableResult.hide() while self.enrichTableResult.rowCount() > 0: self.enrichTableResult.removeRow(0) self.enrichTable.show() self.addEnrichedLayerRowButton.setEnabled(True) fieldnames = [field.name() for field in layer.fields()] while self.enrichTable.rowCount() > 0: self.enrichTable.removeRow(0) row = 0 self.enrichTable.setColumnCount(9) self.enrichTable.setHorizontalHeaderLabels([ "Column", "EnrichmentConcept", "TripleStore", "Strategy", "content", "ID Column", "ID Property", "ID Domain", "Language" ]) for field in fieldnames: item = QTableWidgetItem(field) item.setFlags(QtCore.Qt.ItemIsEnabled) currentRowCount = self.enrichTable.rowCount() self.enrichTable.insertRow(row) self.enrichTable.setItem(row, 0, item) cbox = QComboBox() cbox.addItem("No Enrichment") cbox.addItem("Keep Local") cbox.addItem("Keep Remote") cbox.addItem("Replace Local") cbox.addItem("Merge") cbox.addItem("Ask User") 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.enrichTable.setItem(row, 7, itemm) itemm = QTableWidgetItem("") self.enrichTable.setItem(row, 8, itemm) celllayout = QHBoxLayout() upbutton = QPushButton("Up") removebutton = QPushButton("Remove", self) removebutton.clicked.connect(self.deleteEnrichRow) downbutton = QPushButton("Down") celllayout.addWidget(upbutton) celllayout.addWidget(downbutton) celllayout.addWidget(removebutton) w = QWidget() w.setLayout(celllayout) optitem = QTableWidgetItem() #self.enrichTable.setCellWidget(row,4,w) #self.enrichTable.setItem(row,3,cbox) row += 1 self.originalRowCount = row
def ToggleActiveRow(self, row, value="Playing"): ''' Toggle Active row manager video status ''' self.VManager.setItem(row, 2, QTableWidgetItem(QCoreApplication.translate( "ManagerDock", value))) return
def loadLayerForInterlink(self): layers = QgsProject.instance().layerTreeRoot().children() selectedLayerIndex = self.chooseLayerInterlink.currentIndex() if len(layers) == 0: return layer = layers[selectedLayerIndex].layer() fieldnames = [field.name() for field in layer.fields()] while self.interlinkTable.rowCount() > 0: self.interlinkTable.removeRow(0) row = 0 self.interlinkTable.setHorizontalHeaderLabels([ "Export?", "IDColumn?", "GeoColumn?", "Column", "ColumnProperty", "PropertyType", "ColumnConcept", "ValueConcepts" ]) self.interlinkTable.setColumnCount(8) for field in fieldnames: item = QTableWidgetItem(field) item.setFlags(QtCore.Qt.ItemIsEnabled) item2 = QTableWidgetItem() item2.setCheckState(True) item3 = QTableWidgetItem() item3.setCheckState(False) item4 = QTableWidgetItem() item4.setCheckState(False) self.interlinkTable.insertRow(row) self.interlinkTable.setItem(row, 3, item) self.interlinkTable.setItem(row, 0, item2) self.interlinkTable.setItem(row, 1, item3) self.interlinkTable.setItem(row, 2, item4) cbox = QComboBox() cbox.addItem("Automatic") cbox.addItem("AnnotationProperty") cbox.addItem("DataProperty") cbox.addItem("ObjectProperty") cbox.addItem("SubClass") self.interlinkTable.setCellWidget(row, 5, cbox) currentRowCount = self.interlinkTable.rowCount() row += 1
def addCoord(self, lat, lon, label='', data=[]): '''Add a coordinate to the list.''' rowcnt = self.resultsTable.rowCount() if rowcnt >= self.maxResults: return self.resultsTable.blockSignals(True) self.resultsTable.insertRow(rowcnt) item = QTableWidgetItem(str(lat)) item.setData(Qt.UserRole, LatLonItem(lat, lon, label, data)) item.setFlags(item.flags() & ~Qt.ItemIsEditable) self.resultsTable.setItem(rowcnt, 0, item) item = QTableWidgetItem(str(lon)) item.setFlags(item.flags() & ~Qt.ItemIsEditable) self.resultsTable.setItem(rowcnt, 1, item) self.resultsTable.setItem(rowcnt, 2, QTableWidgetItem(label)) if self.numCol > 3 and len(data) > 0: for i in range(min(self.numCol - 3, len(data))): self.resultsTable.setItem(rowcnt, i + 3, QTableWidgetItem(data[i])) self.resultsTable.blockSignals(False) return(rowcnt)
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())
def applyFilter(self, table, index, filter_value, filter_operation): if filter_value == None: table.filters[index] = None else: if isinstance(filter_value, QDateEdit): table.filters[index] = filter_value.date() elif isinstance(filter_value, QTimeEdit): table.filters[index] = filter_value.time() elif isinstance(filter_value, QDateTimeEdit): table.filters[index] = filter_value.dateTime() else: table.filters[index] = filter_value.text() table.filter_op[index] = filter_operation.currentIndex() nb_elts = 0 for i in range(0, table.rowCount()): table.setRowHidden(i, False) nb_elts += 1 hidden_rows = [] for nb_col in range(0, table.columnCount()): filtered = False header = table.horizontalHeaderItem(nb_col).text() valid = False if table.filters[nb_col] is not None: if type(table.filters[nb_col]) in [QDate, QTime, QDateTime]: valid = True else: if table.filters[nb_col].strip(): valid = True if valid: filtered = True items = None if table.types[nb_col] in [10]:# If it's a string filter_type = None if table.filter_op[nb_col] == 0: # Contain filter_type = Qt.MatchContains if table.filter_op[nb_col] == 1: # Equal filter_type = Qt.MatchFixedString items = table.findItems(table.filters[nb_col], filter_type) elif table.types[nb_col] in [14, 15, 16]: # If it's a date/time items = [] for nb_row in range(0, table.rowCount()): item = table.item(nb_row, nb_col) if table.filter_op[nb_col] == 0: # = if item.data(QTableWidgetItem.Type) == table.filters[nb_col]: items.append(item) if table.filter_op[nb_col] == 1: # > if item.data(QTableWidgetItem.Type) > table.filters[nb_col]: items.append(item) if table.filter_op[nb_col] == 2: # < if item.data(QTableWidgetItem.Type) < table.filters[nb_col]: items.append(item) else: # If it's a number items = [] for nb_row in range(0, table.rowCount()): item = table.item(nb_row, nb_col) if item.text().strip(): if table.filter_op[nb_col] == 0: # = if float(item.text()) == float(table.filters[nb_col]): items.append(item) if table.filter_op[nb_col] == 1: # > if float(item.text()) > float(table.filters[nb_col]): items.append(item) if table.filter_op[nb_col] == 2: # < if float(item.text()) < float(table.filters[nb_col]): items.append(item) rows = [] for item in items: if item.column() == nb_col: rows.append(item.row()) for i in range(0, table.rowCount()): if i not in rows: if i not in hidden_rows: nb_elts -= 1 table.setRowHidden(i, True) hidden_rows.append(i) if filtered: if header[len(header)-1] != '*': table.setHorizontalHeaderItem(nb_col, QTableWidgetItem(header+'*')) else: if header[len(header)-1] == '*': header = header[:-1] table.setHorizontalHeaderItem(nb_col, QTableWidgetItem(header)) title = self.tabWidget.tabText(self.tabWidget.currentIndex()) for i in reversed(range(len(title))): if title[i] == ' ': break title = title[:-1] title += '('+str(nb_elts)+')' self.tabWidget.setTabText(self.tabWidget.currentIndex(), title)
def addLayer(self, layer, headers, types, features): tab = QWidget() tab.layer = layer p1_vertical = QVBoxLayout(tab) p1_vertical.setContentsMargins(0,0,0,0) table = QTableWidget() table.itemSelectionChanged.connect(self.highlight_features) table.title = layer.name() table.crs = layer.crs() table.setColumnCount(len(headers)) if len(features) > 0: table.setRowCount(len(features)) nbrow = len(features) self.loadingWindow.show() self.loadingWindow.setLabelText(table.title) self.loadingWindow.activateWindow() self.loadingWindow.showNormal() # Table population m = 0 for feature in features: n = 0 for cell in feature.attributes(): item = QTableWidgetItem() item.setData(Qt.DisplayRole, cell) item.setFlags(item.flags() ^ Qt.ItemIsEditable) item.feature = feature table.setItem(m, n, item) n += 1 m += 1 self.loadingWindow.setValue(int((float(m)/nbrow)*100)) QApplication.processEvents() else: table.setRowCount(0) table.setHorizontalHeaderLabels(headers) table.horizontalHeader().setSectionsMovable(True) table.types = types table.filter_op = [] table.filters = [] for i in range(0, len(headers)): table.filters.append('') table.filter_op.append(0) header = table.horizontalHeader() header.setContextMenuPolicy(Qt.CustomContextMenu) header.customContextMenuRequested.connect(partial(self.filterMenu, table)) table.setSortingEnabled(True) p1_vertical.addWidget(table) # Status bar to display informations (ie: area) tab.sb = QStatusBar() p1_vertical.addWidget(tab.sb) title = table.title # We reduce the title's length to 20 characters if len(title)>20: title = title[:20]+'...' # We add the number of elements to the tab's title. title += ' ('+str(len(features))+')' self.tabWidget.addTab(tab, title) # Add the tab to the conatiner self.tabWidget.setTabToolTip(self.tabWidget.indexOf(tab), table.title) # Display a tooltip with the layer's full name
def run_stats(self): self.progressBar_stats.setValue(0) self.label_progressStats.setText('') # noinspection PyArgumentList QApplication.processEvents() blurred_layer = self.comboBox_blurredLayer.currentLayer() stats_layer = self.comboBox_statsLayer.currentLayer() try: if not blurred_layer or not stats_layer: raise NoLayerProvidedException crs_blurred_layer = blurred_layer.crs() crs_stats_layer = stats_layer.crs() if crs_blurred_layer != crs_stats_layer: raise DifferentCrsException( epsg1=crs_blurred_layer.authid(), epsg2=crs_stats_layer.authid()) if blurred_layer == stats_layer: raise NoLayerProvidedException if not blurred_layer or not stats_layer: raise NoLayerProvidedException nb_feature_stats = stats_layer.featureCount() nb_feature_blurred = blurred_layer.featureCount() features_stats = {} label_preparing = tr('Preparing index on the stats layer') label_creating = tr('Creating index on the stats layer') label_calculating = tr('Calculating') if Qgis.QGIS_VERSION_INT < 20700: self.label_progressStats.setText('%s 1/3' % label_preparing) for i, feature in enumerate(stats_layer.getFeatures()): features_stats[feature.id()] = feature percent = int((i + 1) * 100 / nb_feature_stats) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() self.label_progressStats.setText('%s 2/3' % label_creating) # noinspection PyArgumentList QApplication.processEvents() index = QgsSpatialIndex() for i, f in enumerate(stats_layer.getFeatures()): index.insertFeature(f) percent = int((i + 1) * 100 / nb_feature_stats) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() self.label_progressStats.setText('%s 3/3' % label_calculating) else: # If QGIS >= 2.7, we can speed up the spatial index. # From 1 min 15 to 7 seconds on my PC. self.label_progressStats.setText('%s 1/2' % label_creating) # noinspection PyArgumentList QApplication.processEvents() index = QgsSpatialIndex(stats_layer.getFeatures()) self.label_progressStats.setText('%s 2/2' % label_calculating) # noinspection PyArgumentList QApplication.processEvents() self.tab = [] for i, feature in enumerate(blurred_layer.getFeatures()): count = 0 ids = index.intersects(feature.geometry().boundingBox()) for unique_id in ids: request = QgsFeatureRequest().setFilterFid(unique_id) f = next(stats_layer.getFeatures(request)) if f.geometry().intersects(feature.geometry()): count += 1 self.tab.append(count) percent = int((i + 1) * 100 / nb_feature_blurred) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() stats = Stats(self.tab) items_stats = [ 'Count(blurred),%d' % nb_feature_blurred, 'Count(stats),%d' % nb_feature_stats, 'Min,%d' % stats.min(), 'Average,%f' % stats.average(), 'Max,%d' % stats.max(), 'Median,%f' % stats.median(), 'Range,%d' % stats.range(), 'Variance,%f' % stats.variance(), 'Standard deviation,%f' % stats.standard_deviation() ] self.tableWidget.clear() self.tableWidget.setColumnCount(2) labels = ['Parameters', 'Values'] self.tableWidget.setHorizontalHeaderLabels(labels) self.tableWidget.setRowCount(len(items_stats)) for i, item in enumerate(items_stats): s = item.split(',') self.tableWidget.setItem(i, 0, QTableWidgetItem(s[0])) self.tableWidget.setItem(i, 1, QTableWidgetItem(s[1])) self.tableWidget.resizeRowsToContents() self.draw_plot(self.tab) except GeoPublicHealthException as e: self.label_progressStats.setText('') display_message_bar(msg=e.msg, level=e.level, duration=e.duration)
def insertParams(self, position, distance, startAngle, endAngle): if position > self.tableWidget.rowCount(): self.tableWidget.insertRow(position - 1) item = QTableWidgetItem('{:.4f}'.format(self.unitDistance(distance))) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.tableWidget.setItem(position - 1, 2, item) item = QTableWidgetItem('{:.4f}'.format(startAngle)) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.tableWidget.setItem(position - 1, 0, item) item = QTableWidgetItem('{:.4f}'.format(endAngle)) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.tableWidget.setItem(position - 1, 1, item)
def addLUDataFields(self): self.LUtableClear() layer = self.setLULayer() if layer: dp = layer.dataProvider() features = layer.selectedFeatures() attrs = [] for feat in features: attr = feat.attributes() attrs.append(attr) idfieldindex = dp.fieldNameIndex(LanduseTool.lu_id_attribute) floorfieldindex = dp.fieldNameIndex(LanduseTool.floors_attribute) areafieldindex = dp.fieldNameIndex(LanduseTool.area_attribute) gfcatfieldindex = dp.fieldNameIndex(LanduseTool.gf_cat_attribute) gfsubcatfieldindex = dp.fieldNameIndex( LanduseTool.gf_subcat_attribute) lfcatfieldindex = dp.fieldNameIndex(LanduseTool.lf_cat_attribute) lfsubcatfieldindex = dp.fieldNameIndex( LanduseTool.lf_subcat_attribute) ufcatfieldindex = dp.fieldNameIndex(LanduseTool.uf_cat_attribute) ufsubcatfieldindex = dp.fieldNameIndex( LanduseTool.uf_subcat_attribute) self.tableWidgetlanduse.setColumnCount(5) self.tableWidgetlanduse.setRowCount(len(attrs)) if self.LUGroundfloorradioButton.isChecked(): headers = [ "LU-ID", "Floors", "Area", "GF Category", "GF Sub Category" ] self.tableWidgetlanduse.setHorizontalHeaderLabels(headers) for i, item in enumerate(attrs): self.tableWidgetlanduse.setItem( i, 0, QTableWidgetItem(str(item[idfieldindex]))) self.tableWidgetlanduse.setItem( i, 1, QTableWidgetItem(str(item[floorfieldindex]))) self.tableWidgetlanduse.setItem( i, 2, QTableWidgetItem(str(item[areafieldindex]))) self.tableWidgetlanduse.setItem( i, 3, QTableWidgetItem(str(item[gfcatfieldindex]))) self.tableWidgetlanduse.setItem( i, 4, QTableWidgetItem(str(item[gfsubcatfieldindex]))) elif self.LULowerfloorradioButton.isChecked(): headers = [ "LU-ID", "Floors", "Area", "LF Category", "LF Sub Category" ] self.tableWidgetlanduse.setHorizontalHeaderLabels(headers) for i, item in enumerate(attrs): self.tableWidgetlanduse.setItem( i, 0, QTableWidgetItem(str(item[idfieldindex]))) self.tableWidgetlanduse.setItem( i, 1, QTableWidgetItem(str(item[floorfieldindex]))) self.tableWidgetlanduse.setItem( i, 2, QTableWidgetItem(str(item[areafieldindex]))) self.tableWidgetlanduse.setItem( i, 3, QTableWidgetItem(str(item[lfcatfieldindex]))) self.tableWidgetlanduse.setItem( i, 4, QTableWidgetItem(str(item[lfsubcatfieldindex]))) elif self.LUUpperfloorradioButton.isChecked(): headers = [ "LU-ID", "Floors", "Area", "UF Category", "UF Sub Category" ] self.tableWidgetlanduse.setHorizontalHeaderLabels(headers) for i, item in enumerate(attrs): self.tableWidgetlanduse.setItem( i, 0, QTableWidgetItem(str(item[idfieldindex]))) self.tableWidgetlanduse.setItem( i, 1, QTableWidgetItem(str(item[floorfieldindex]))) self.tableWidgetlanduse.setItem( i, 2, QTableWidgetItem(str(item[areafieldindex]))) self.tableWidgetlanduse.setItem( i, 3, QTableWidgetItem(str(item[ufcatfieldindex]))) self.tableWidgetlanduse.setItem( i, 4, QTableWidgetItem(str(item[ufsubcatfieldindex]))) self.tableWidgetlanduse.resizeRowsToContents() self.tableWidgetlanduse.resizeColumnsToContents() self.tableWidgetlanduse.horizontalHeader().setResizeMode( 4, QHeaderView.Stretch)
def buscar(self): self.datos = self.dlg.leBusqueda_4.text() envio = {} envio['folio'] = self.datos envio['solicitante'] = self.datos resp = self.guardarOperacion(nuevo=self.nuevo, url=(self.CFG.urlOptenerTramites), envio=envio) #print(resp) self.dlg.twOperaciones_9.clearContents() self.dlg.twOperaciones_9.setRowCount(0) if resp == []: self.createAlert('Ingrese un Folio correcta o un nombre correcto', QMessageBox().Critical, "Solicitud") # mostrar usuarios en tabla self.dlg.twOperaciones_9.setRowCount(len(resp)) for x in range(0, len(resp)): item2 = QTableWidgetItem(str(resp[x]['fecha_solcitud'])) item3 = QTableWidgetItem(str(resp[x]['clave_catastral'])) item4 = QTableWidgetItem(str(resp[x]['solicita_localidad'])) item5 = QTableWidgetItem(str(resp[x]['folio_inicio'])) item6 = QTableWidgetItem(str(resp[x]['propietario'])) item7 = QTableWidgetItem(str(resp[x]['solicita_nombre'])) item8 = QTableWidgetItem(str(resp[x]['idTramite'])) item9 = QTableWidgetItem(str(resp[x]['solicita_tel'])) item10 = QTableWidgetItem(str(resp[x]['solicita_municipio'])) item11 = QTableWidgetItem(str(resp[x]['id'])) item12 = QTableWidgetItem(str(resp[x]['solicita_colonia'])) item13 = QTableWidgetItem(str(resp[x]['solicita_fraccionamiento'])) item14 = QTableWidgetItem(str(resp[x]['solicita_correo'])) item15 = QTableWidgetItem(str(resp[x]['solicita_calle'])) self.dlg.twOperaciones_9.setItem(x, 0, item2) self.dlg.twOperaciones_9.setItem(x, 1, item3) self.dlg.twOperaciones_9.setItem(x, 2, item4) self.dlg.twOperaciones_9.setItem(x, 3, item5) self.dlg.twOperaciones_9.setItem(x, 4, item6) self.dlg.twOperaciones_9.setItem(x, 5, item7) self.dlg.twOperaciones_9.setItem(x, 6, item8) self.dlg.twOperaciones_9.setItem(x, 7, item9) self.dlg.twOperaciones_9.setItem(x, 8, item10) self.dlg.twOperaciones_9.setItem(x, 9, item11) self.dlg.twOperaciones_9.setItem(x, 10, item12) self.dlg.twOperaciones_9.setItem(x, 11, item13) self.dlg.twOperaciones_9.setItem(x, 12, item14) self.dlg.twOperaciones_9.setItem(x, 13, item15)
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
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()
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 = [lyr.name() for lyr in mc.layers()] 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 layer are missing, you dick" for lyr in missing_layers: msg += f"\n{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: lyrNests = QgsProject.instance().mapLayersByName("Raptor Nests")[0] lyrBuffer = QgsProject.instance().mapLayersByName( "Raptor Buffer")[0] lyrLinear = QgsProject.instance().mapLayersByName( "Linear Buffer")[0] 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", f"New Nest ID: {valNestID}\n\n{valLat}\n\n{valLng}\n\n{valSpecies}\n\n{valBuffer}\n\n{valStatus}\n\n{valLast}" ) 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) pr = lyrNests.dataProvider() pr.addFeatures([ftrNest]) lyrNests.reload() 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 impacted linear projects 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(str(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 canceled")
def update_local_data_sources(self, local_layers, local_raster_layers): # update table names lookup local_layers += local_raster_layers self.update_data_sources_table_names() self.local_data_sources.update_local_data_sources(local_layers) # update GUI self.ui.tblLocalLayers.setRowCount(0) schema_list = [] if self.ui.cbUploadDatabase.count() == 1: schema_list = self.fetch_schemas(self.ui.cbUploadDatabase.currentText()) elif self.ui.cbUploadDatabase.currentIndex() > 0: schema_list = self.fetch_schemas(self.ui.cbUploadDatabase.currentText()) for data_source, layers in list(self.local_data_sources.iteritems()): layer_names = [] for layer in layers: layer_names.append(str(layer.name())) layers_item = QTableWidgetItem(", ".join(layer_names)) layers_item.setToolTip("\n".join(layer_names)) data_source_item = QTableWidgetItem(data_source) data_source_item.setToolTip(data_source) # find a better table name if there are multiple layers with same # data source? table_name = layers[0].name() if data_source in self.data_sources_table_names: # use current table name if available to keep changes by user table_name = self.data_sources_table_names[data_source] table_name_item = QTableWidgetItem(self.launder_pg_name(table_name)) if layers[0].providerType() == 'gdal': geometry_type_item = QTableWidgetItem('Raster') else: wkbType = layers[0].wkbType() if wkbType not in self.GEOMETRY_TYPES: QMessageBox.warning(self.iface.mainWindow(), self.tr("Unsupported geometry type"), self.tr( "Unsupported geometry type '{type}' in layer '{layer}'").format(type=self.__wkbTypeString(wkbType), layer=layers[0].name())) continue geometry_type_item = QTableWidgetItem(self.GEOMETRY_TYPES[wkbType]) if layers[0].providerType() == "ogr": geometry_type_item.setToolTip( self.tr("Note: OGR features will be converted to MULTI-type")) srid_item = QTableWidgetItem(layers[0].crs().authid()) row = self.ui.tblLocalLayers.rowCount() self.ui.tblLocalLayers.insertRow(row) layers_item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled ) self.ui.tblLocalLayers.setItem( row, self.COLUMN_LAYERS, layers_item) data_source_item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled ) self.ui.tblLocalLayers.setItem( row, self.COLUMN_DATA_SOURCE, data_source_item) # create combo box in schema column filled with all schema names of the selected database cmb_schema = QComboBox() cmb_schema.setEditable(True) cmb_schema.addItems(schema_list) self.ui.tblLocalLayers.setCellWidget(row, self.COLUMN_SCHEMA_NAME, cmb_schema) table_name_item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled ) self.ui.tblLocalLayers.setItem( row, self.COLUMN_TABLE_NAME, table_name_item) geometry_type_item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled ) self.ui.tblLocalLayers.setItem( row, self.COLUMN_GEOMETRY_TYPE, geometry_type_item) srid_item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled ) self.ui.tblLocalLayers.setItem(row, self.COLUMN_SRID, srid_item) if self.local_data_sources.count() > 0: self.ui.tblLocalLayers.resizeColumnsToContents() self.ui.tblLocalLayers.setColumnWidth(self.COLUMN_LAYERS, 100) self.ui.tblLocalLayers.setColumnWidth(self.COLUMN_DATA_SOURCE, 100) self.ui.tblLocalLayers.sortItems(self.COLUMN_DATA_SOURCE) self.ui.tblLocalLayers.setSortingEnabled(False) else: self.ui.btnUploadData.setEnabled(False) self.statusBar().showMessage(self.tr("Updated local data sources"))
def AddFileRowToManager(self, name, filename, load_id=None, islocal=False, klv_folder=None): """ Add file Video to new Row """ # We limit the number of videos due to the buffer self.loading = True if self.VManager.rowCount() > 5: qgsu.showUserAndLogMessage( QCoreApplication.translate( "ManagerDock", "You must delete some video from the list before adding a new one", ), level=QGis.Warning, ) self.loading = False return self.islocal = islocal self.klv_folder = klv_folder w = QWidget() layout = QVBoxLayout() pbar = QProgressBar() layout.addWidget(pbar) w.setLayout(layout) rowPosition = self.VManager.rowCount() self.videoPlayable.append(False) pbar.setGeometry(0, 0, 300, 30) pbar.setValue(0) pbar.setMaximumHeight(30) if load_id is None: row_id = 0 if rowPosition != 0: row_id = int(self.VManager.item(rowPosition - 1, 0).text()) + 1 else: row_id = load_id self.VManager.insertRow(rowPosition) self.VManager.setItem(rowPosition, 0, QTableWidgetItem(str(row_id))) self.VManager.setItem(rowPosition, 1, QTableWidgetItem(name)) self.VManager.setItem( rowPosition, 2, QTableWidgetItem( QCoreApplication.translate("ManagerDock", "Loading")), ) self.VManager.setItem(rowPosition, 3, QTableWidgetItem(filename)) self.VManager.setItem(rowPosition, 4, QTableWidgetItem("-")) self.VManager.setCellWidget(rowPosition, 5, w) self.VManager.setVisible(False) self.VManager.horizontalHeader().setStretchLastSection(True) self.VManager.setVisible(True) # resolve if it is a stream if "://" in filename: self.videoIsStreaming.append(True) else: self.videoIsStreaming.append(False) if not self.videoIsStreaming[-1]: # Disable row if not exist video file if not os.path.exists(filename): self.ToggleActiveRow(rowPosition, value="Missing source file") for j in range(self.VManager.columnCount()): try: self.VManager.item(rowPosition, j).setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled) self.VManager.item(rowPosition, j).setBackground( QColor(211, 211, 211)) except Exception: self.VManager.cellWidget(rowPosition, j).setStyleSheet( "background-color:rgb(211,211,211);") pass self.loading = False return pbar.setValue(30) info = FFMpeg().probe(filename) if info is None: qgsu.showUserAndLogMessage( QCoreApplication.translate("ManagerDock", "Failed loading FFMPEG ! ")) klvIdx = getKlvStreamIndex(filename, islocal) # init non-blocking metadata buffered reader self.meta_reader.append( BufferedMetaReader( filename, klv_index=klvIdx, pass_time=self.pass_time, interval=self.buf_interval, )) pbar.setValue(60) try: # init point we can center the video on self.initialPt.append( getVideoLocationInfo(filename, islocal, klv_folder)) if not self.initialPt[rowPosition]: self.VManager.setItem( rowPosition, 4, QTableWidgetItem( QCoreApplication.translate( "ManagerDock", "Start location not available.")), ) self.ToggleActiveRow(rowPosition, value="Video not applicable") pbar.setValue(100) else: self.VManager.setItem( rowPosition, 4, QTableWidgetItem(self.initialPt[rowPosition][2])) pbar.setValue(90) self.videoPlayable[rowPosition] = True except Exception: qgsu.showUserAndLogMessage( QCoreApplication.translate( "ManagerDock", "This video doesn't have Metadata ! ")) pbar.setValue(100) self.ToggleActiveRow(rowPosition, value="Video not applicable") else: self.meta_reader.append(StreamMetaReader(filename)) qgsu.showUserAndLogMessage("", "StreamMetaReader initialized.", onlyLog=True) self.initialPt.append(None) self.videoPlayable[rowPosition] = True url = "" if self.videoIsStreaming[-1]: # show video from splitter (port +1) oldPort = filename.split(":")[2] newPort = str(int(oldPort) + 10) proto = filename.split(":")[0] url = QUrl(proto + "://127.0.0.1:" + newPort) else: url = QUrl.fromLocalFile(filename) self.playlist.addMedia(QMediaContent(url)) if self.videoPlayable[rowPosition]: pbar.setValue(100) if islocal: self.ToggleActiveRow(rowPosition, value="Ready Local") else: self.ToggleActiveRow(rowPosition, value="Ready") # Add video to settings list AddVideoToSettings(str(row_id), filename) self.loading = False
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")
def loadModels(self, error=True): self.settings.servicE = self.leSERVICE.text() self.settings.host = self.leHOST.text() self.settings.port = self.lePORT.text() self.settings.dbname = self.leDBNAME.text() self.settings.schema = self.leSCHEMA.text() self.settings.uid = self.leUID.text() self.settings.pwd = self.lePWD.text() if hasattr(qgis.gui, 'QgsAuthConfigSelect'): self.settings.authcfg = self.authCfgSelect.configId() self.twModellarten.clearContents() self.cbxSignaturkatalog.clear() (db, conninfo) = self.plugin.opendb() if not db: if error: QMessageBox.critical(None, "ALKIS", u"Datenbankverbindung schlug fehl.") self.twModellarten.clearContents() self.twModellarten.setDisabled(True) self.twModellarten.setRowCount(0) self.settings.load() return modelle = self.settings.modellarten if modelle is None: modelle = ['DLKM', 'DKKM1000'] qry = QSqlQuery(db) if qry.exec_("SELECT 1 FROM information_schema.tables WHERE table_schema={} AND table_name='po_modelle'".format(quote(self.plugin.settings.schema))) and qry.next(): sql = "SELECT modell,n FROM po_modelle WHERE modell IS NOT NULL ORDER BY n DESC" else: sql = """ SELECT modell,count(*) FROM ( SELECT unnest(modell) AS modell FROM po_points UNION ALL SELECT unnest(modell) AS modell FROM po_lines UNION ALL SELECT unnest(modell) AS modell FROM po_polygons UNION ALL SELECT unnest(modell) AS modell from po_labels ) AS foo WHERE modell IS NOT NULL GROUP BY modell ORDER BY count(*) DESC """ if qry.exec_(sql): res = {} while qry.next(): res[qry.value(0)] = qry.value(1) self.twModellarten.setRowCount(len(res)) i = 0 for k, n in sorted(iter(list(res.items())), key=operator.itemgetter(1), reverse=True): item = QTableWidgetItem(k) item.setCheckState(Qt.Checked if (item.text() in modelle) else Qt.Unchecked) self.twModellarten.setItem(i, 0, item) item = QTableWidgetItem(str(n)) self.twModellarten.setItem(i, 1, item) i += 1 self.twModellarten.resizeColumnsToContents() self.twModellarten.setEnabled(True) else: self.twModellarten.clearContents() self.twModellarten.setDisabled(True) self.twModellarten.setRowCount(0) if qry.exec_("SELECT id,name FROM alkis_signaturkataloge"): while qry.next(): self.cbxSignaturkatalog.addItem(qry.value(1), int(qry.value(0))) self.cbxSignaturkatalog.setEnabled(True) else: self.cbxSignaturkatalog.addItem(u"Farbe", -1) self.cbxSignaturkatalog.setCurrentIndex(max([0, self.cbxSignaturkatalog.findData(self.settings.signaturkatalog)])) self.settings.load()
def insertProp(self, description, val1, val2=None): self.tableWidget.insertRow(self.count) item = QTableWidgetItem(unicode(description)) item.setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.tableWidget.setItem(self.count, 0, item) item = QTableWidgetItem(unicode(val1)) item.setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.tableWidget.setItem(self.count, 1, item) if val2 is not None: item = QTableWidgetItem(unicode(val2)) item.setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.tableWidget.setItem(self.count, 2, item) self.count += 1
def checkbox(): item = QTableWidgetItem() item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) item.setCheckState(Qt.Unchecked) return item
def restoreSettings(self): settings = QgsSettings() font = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.spinBox.setValue(settings.value("pythonConsole/fontsize", font.pointSize(), type=int)) self.spinBoxEditor.setValue(settings.value("pythonConsole/fontsizeEditor", font.pointSize(), type=int)) self.fontComboBox.setCurrentFont(QFont(settings.value("pythonConsole/fontfamilytext", font.family()))) self.fontComboBoxEditor.setCurrentFont(QFont(settings.value("pythonConsole/fontfamilytextEditor", font.family()))) self.preloadAPI.setChecked(settings.value("pythonConsole/preloadAPI", True, type=bool)) self.lineEdit.setText(settings.value("pythonConsole/preparedAPIFile", "", type=str)) itemTable = settings.value("pythonConsole/userAPI", []) if itemTable: self.tableWidget.setRowCount(0) for i in range(len(itemTable)): self.tableWidget.insertRow(i) self.tableWidget.setColumnCount(2) pathSplit = itemTable[i].split("/") apiName = pathSplit[-1][0:-4] self.tableWidget.setItem(i, 0, QTableWidgetItem(apiName)) self.tableWidget.setItem(i, 1, QTableWidgetItem(itemTable[i])) self.autoSaveScript.setChecked(settings.value("pythonConsole/autoSaveScript", False, type=bool)) self.autoCompThreshold.setValue(settings.value("pythonConsole/autoCompThreshold", 2, type=int)) self.autoCompThresholdEditor.setValue(settings.value("pythonConsole/autoCompThresholdEditor", 2, type=int)) self.groupBoxAutoCompletionEditor.setChecked( settings.value("pythonConsole/autoCompleteEnabledEditor", True, type=bool)) self.groupBoxAutoCompletion.setChecked(settings.value("pythonConsole/autoCompleteEnabled", True, type=bool)) self.enableObjectInspector.setChecked(settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.autoCloseBracketEditor.setChecked(settings.value("pythonConsole/autoCloseBracketEditor", False, type=bool)) self.autoCloseBracket.setChecked(settings.value("pythonConsole/autoCloseBracket", False, type=bool)) self.autoInsertionImportEditor.setChecked( settings.value("pythonConsole/autoInsertionImportEditor", True, type=bool)) self.autoInsertionImport.setChecked(settings.value("pythonConsole/autoInsertionImport", True, type=bool)) if settings.value("pythonConsole/autoCompleteSource") == 'fromDoc': self.autoCompFromDoc.setChecked(True) elif settings.value("pythonConsole/autoCompleteSource") == 'fromAPI': self.autoCompFromAPI.setChecked(True) elif settings.value("pythonConsole/autoCompleteSource") == 'fromDocAPI': self.autoCompFromDocAPI.setChecked(True) if settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromDoc': self.autoCompFromDocEditor.setChecked(True) elif settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromAPI': self.autoCompFromAPIEditor.setChecked(True) elif settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromDocAPI': self.autoCompFromDocAPIEditor.setChecked(True) # Setting font lexer color self.defaultFontColor.setColor(QColor(settings.value("pythonConsole/defaultFontColor", QColor(Qt.black)))) self.defaultFontColorEditor.setColor( QColor(settings.value("pythonConsole/defaultFontColorEditor", QColor(Qt.black)))) self.keywordFontColor.setColor(QColor(settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen)))) self.keywordFontColorEditor.setColor( QColor(settings.value("pythonConsole/keywordFontColorEditor", QColor(Qt.darkGreen)))) self.classFontColor.setColor(QColor(settings.value("pythonConsole/classFontColor", QColor(Qt.blue)))) self.classFontColorEditor.setColor( QColor(settings.value("pythonConsole/classFontColorEditor", QColor(Qt.blue)))) self.methodFontColor.setColor(QColor(settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray)))) self.methodFontColorEditor.setColor( QColor(settings.value("pythonConsole/methodFontColorEditor", QColor(Qt.darkGray)))) self.decorFontColor.setColor(QColor(settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue)))) self.decorFontColorEditor.setColor( QColor(settings.value("pythonConsole/decorFontColorEditor", QColor(Qt.darkBlue)))) self.commentFontColor.setColor(QColor(settings.value("pythonConsole/commentFontColor", QColor(Qt.gray)))) self.commentFontColorEditor.setColor( QColor(settings.value("pythonConsole/commentFontColorEditor", QColor(Qt.gray)))) self.commentBlockFontColor.setColor( QColor(settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray)))) self.commentBlockFontColorEditor.setColor( QColor(settings.value("pythonConsole/commentBlockFontColorEditor", QColor(Qt.gray)))) self.paperBackgroundColor.setColor( QColor(settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))) self.paperBackgroundColorEditor.setColor( QColor(settings.value("pythonConsole/paperBackgroundColorEditor", QColor(Qt.white)))) self.caretLineColor.setColor(QColor(settings.value("pythonConsole/caretLineColor", QColor("#fcf3ed")))) self.caretLineColorEditor.setColor( QColor(settings.value("pythonConsole/caretLineColorEditor", QColor("#fcf3ed")))) self.cursorColor.setColor(QColor(settings.value("pythonConsole/cursorColor", QColor(Qt.black)))) self.cursorColorEditor.setColor(QColor(settings.value("pythonConsole/cursorColorEditor", QColor(Qt.black)))) self.stderrFontColor.setColor(QColor(settings.value("pythonConsole/stderrFontColor", QColor(Qt.red)))) self.singleQuoteFontColor.setColor(settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))) self.singleQuoteFontColorEditor.setColor( settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(Qt.blue))) self.doubleQuoteFontColor.setColor(settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))) self.doubleQuoteFontColorEditor.setColor( settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(Qt.blue))) self.tripleSingleQuoteFontColor.setColor( settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))) self.tripleSingleQuoteFontColorEditor.setColor( settings.value("pythonConsole/tripleSingleQuoteFontColorEditor", QColor(Qt.blue))) self.tripleDoubleQuoteFontColor.setColor( settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))) self.tripleDoubleQuoteFontColorEditor.setColor( settings.value("pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(Qt.blue)))
def reloadProject(self): """ Load all layers from the map layer registry into the table. """ self.unsupportedLayersList = list() self.photoNamingTable.setRowCount(0) self.layersTable.setRowCount(0) self.layersTable.setSortingEnabled(False) for layer in self.project.mapLayers().values(): layer_source = LayerSource(layer) count = self.layersTable.rowCount() self.layersTable.insertRow(count) item = QTableWidgetItem(layer.name()) item.setData(Qt.UserRole, layer_source) item.setData(Qt.EditRole, layer.name()) self.layersTable.setItem(count, 0, item) cmb = QComboBox() set_available_actions(cmb, layer_source) cbx = QCheckBox() cbx.setEnabled(layer_source.can_lock_geometry) cbx.setChecked(layer_source.is_geometry_locked) # it's more UI friendly when the checkbox is centered, an ugly workaround to achieve it cbx_widget = QWidget() cbx_layout = QHBoxLayout() cbx_layout.setAlignment(Qt.AlignCenter) cbx_layout.setContentsMargins(0, 0, 0, 0) cbx_layout.addWidget(cbx) cbx_widget.setLayout(cbx_layout) # NOTE the margin is not updated when the table column is resized, so better rely on the code above # cbx.setStyleSheet("margin-left:50%; margin-right:50%;") self.layersTable.setCellWidget(count, 1, cbx_widget) self.layersTable.setCellWidget(count, 2, cmb) if not layer_source.is_supported: self.unsupportedLayersList.append(layer_source) self.layersTable.item(count, 0).setFlags(Qt.NoItemFlags) self.layersTable.cellWidget(count, 1).setEnabled(False) self.layersTable.cellWidget(count, 2).setEnabled(False) cmb.setCurrentIndex(cmb.findData(SyncAction.REMOVE)) # make sure layer_source is the same instance everywhere self.photoNamingTable.addLayerFields(layer_source) self.layersTable.resizeColumnsToContents() self.layersTable.sortByColumn(0, Qt.AscendingOrder) self.layersTable.setSortingEnabled(True) # Remove the tab when not yet suported in QGIS if Qgis.QGIS_VERSION_INT < 31300: self.tabWidget.removeTab(self.tabWidget.count() - 1) # Load Map Themes for theme in self.project.mapThemeCollection().mapThemes(): self.mapThemeComboBox.addItem(theme) self.layerComboBox.setFilters(QgsMapLayerProxyModel.RasterLayer) self.__project_configuration = ProjectConfiguration(self.project) self.createBaseMapGroupBox.setChecked( self.__project_configuration.create_base_map) if self.__project_configuration.base_map_type == ProjectProperties.BaseMapType.SINGLE_LAYER: self.singleLayerRadioButton.setChecked(True) else: self.mapThemeRadioButton.setChecked(True) self.mapThemeComboBox.setCurrentIndex( self.mapThemeComboBox.findText( self.__project_configuration.base_map_theme)) layer = QgsProject.instance().mapLayer( self.__project_configuration.base_map_layer) self.layerComboBox.setLayer(layer) self.mapUnitsPerPixel.setText( str(self.__project_configuration.base_map_mupp)) self.tileSize.setText( str(self.__project_configuration.base_map_tile_size)) self.onlyOfflineCopyFeaturesInAoi.setChecked( self.__project_configuration.offline_copy_only_aoi) if self.unsupportedLayersList: self.unsupportedLayersLabel.setVisible(True) unsupported_layers_text = '<b>{}: </b>'.format(self.tr('Warning')) unsupported_layers_text += self.tr( "There are unsupported layers in your project which will not be available in QField." ) unsupported_layers_text += self.tr( " If needed, you can create a Base Map to include those layers in your packaged project." ) self.unsupportedLayersLabel.setText(unsupported_layers_text)
def AddFileRowToManager(self, name, filename, load_id=None, islocal=False, klv_folder=None): ''' Add file Video to new Row ''' # We limit the number of videos due to the buffer if self.VManager.rowCount() > 5: qgsu.showUserAndLogMessage(QCoreApplication.translate( "ManagerDock", "You must delete some video from the list before adding a new one")) return self.islocal = islocal self.klv_folder = klv_folder w = QWidget() layout = QVBoxLayout() pbar = QProgressBar() layout.addWidget(pbar) w.setLayout(layout) rowPosition = self.VManager.rowCount() pbar.setGeometry(0, 0, 300, 30) pbar.setValue(0) pbar.setMaximumHeight(30) if load_id is None: row_id = 0 if rowPosition != 0: row_id = int(self.VManager.item(rowPosition - 1, 0).text()) + 1 else: row_id = load_id self.VManager.insertRow(rowPosition) self.VManager.setItem( rowPosition, 0, QTableWidgetItem(str(row_id))) self.VManager.setItem(rowPosition, 1, QTableWidgetItem(name)) self.VManager.setItem(rowPosition, 2, QTableWidgetItem(QCoreApplication.translate( "ManagerDock", "Loading"))) self.VManager.setItem(rowPosition, 3, QTableWidgetItem(filename)) self.VManager.setItem(rowPosition, 4, QTableWidgetItem("-")) self.VManager.setCellWidget(rowPosition, 5, w) self.VManager.setVisible(False) self.VManager.horizontalHeader().setStretchLastSection(True) self.VManager.setVisible(True) # Disable row if not exist video file if not os.path.exists(filename): self.ToggleActiveRow(rowPosition, value="Missing source file") for j in range(self.VManager.columnCount()): try: self.VManager.item(rowPosition, j).setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled) self.VManager.item(rowPosition, j).setBackground(QColor(211, 211, 211)) except Exception: self.VManager.cellWidget(rowPosition, j).setStyleSheet("background-color:rgb(211,211,211);"); pass return pbar.setValue(30) if not self.isStreaming: info = FFMpeg().probe(filename) if info is None: qgsu.showUserAndLogMessage(QCoreApplication.translate( "ManagerDock", "Failed loading FFMPEG ! ")) return info.format.duration # init non-blocking metadata buffered reader self.meta_reader[str(rowPosition)] = BufferedMetaReader(filename, pass_time=self.pass_time) qgsu.showUserAndLogMessage( "", "buffered non-blocking metadata reader initialized.", onlyLog=True) pbar.setValue(60) try: # init point we can center the video on self.initialPt[str(rowPosition) ] = getVideoLocationInfo(filename, islocal, klv_folder) if not self.initialPt[str(rowPosition)]: self.VManager.setItem(rowPosition, 4, QTableWidgetItem( QCoreApplication.translate( "ManagerDock", "Start location not available."))) self.ToggleActiveRow(rowPosition, value="Not MISB") pbar.setValue(99) return else: self.VManager.setItem(rowPosition, 4, QTableWidgetItem( self.initialPt[str(rowPosition)][2])) except Exception: qgsu.showUserAndLogMessage(QCoreApplication.translate( "ManagerDock", "This video don't have Metadata ! ")) pbar.setValue(99) self.ToggleActiveRow(rowPosition, value="Not MISB") return pbar.setValue(90) dtm_path = parser['GENERAL']['DTM_file'] if self.initialPt[str(rowPosition)] and dtm_path != '': try: initElevationModel(self.initialPt[str( rowPosition)][0], self.initialPt[str(rowPosition)][1], dtm_path) qgsu.showUserAndLogMessage( "", "Elevation model initialized.", onlyLog=True) except Exception: None else: self.meta_reader[str(rowPosition)] = None self.initialPt[str(rowPosition)] = None pbar.setValue(100) if islocal: self.ToggleActiveRow(rowPosition, value="Ready Local") else: self.ToggleActiveRow(rowPosition, value="Ready") # Add video to settings list AddVideoToSettings(str(row_id), filename)
def predictionsResolved(self): # Check to see if the resolved signal is for data we currently care about. # if not, then just bail if self.stationData is None or self.stationData.state != PredictionPromise.ResolvedState: return """ when we have predictions for the current station, show them in the plot and table widget. """ if self.predictionCanvas is not None: self.predictionCanvas.mpl_disconnect(self.plotCallbackId) self.plotLayout.removeWidget(self.predictionCanvas) self.predictionCanvas.hide() self.predictionCanvas = FigureCanvas(Figure(figsize=(5, 3))) self.plotLayout.addWidget(self.predictionCanvas) self.plotAxes = self.predictionCanvas.figure.subplots() # zero time in this plot = 00:00 local time on the date of interest t0 = QDateTime(self.dateEdit.date(), QTime(0, 0), stationTimeZone(self.stationFeature)).toUTC() t = [] val = [] for f in self.stationData.predictions: if f['type'] == 'current': utcTime = f['time'] utcTime.setTimeSpec(Qt.TimeSpec.UTC) t.append(t0.secsTo(utcTime) / 3600) val.append(f['value']) self.plotAxes.set_xlim(left=0, right=24) self.plotAxes.set_xticks([0, 3, 6, 9, 12, 15, 18, 21, 24]) self.plotAxes.grid(linewidth=0.5) y0line = self.plotAxes.axhline(y=0) y0line.set_linestyle(':') y0line.set_linewidth(1) self.plotXLine = self.plotAxes.axvline(x=0) self.plotXLine.set_linestyle(':') self.plotXLine.set_linewidth(1) self.updatePlotXLine() self.plotAxes.plot(t, val) self.plotCallbackId = self.predictionCanvas.mpl_connect( 'button_release_event', self.handlePlotClick) QgsProject.instance()._ax = self.plotAxes self.tableWidget.setRowCount(len(self.stationData.predictions)) i = 0 for p in self.stationData.predictions: dt = p['time'] dt.setTimeSpec(Qt.TimeSpec.UTC) if self.includeCurrentsInTable and p[ 'type'] == 'current' and p['dir'] != NULL: self.tableWidget.setItem( i, 0, QTableWidgetItem( dt.toTimeZone(self.stationZone).toString('h:mm AP'))) self.tableWidget.setItem( i, 1, QTableWidgetItem(str(round(p['dir'])) + 'ยบ')) self.tableWidget.setItem( i, 2, QTableWidgetItem("{:.2f}".format(p['magnitude']))) i += 1 elif p['type'] != 'current': self.tableWidget.setItem( i, 0, QTableWidgetItem( dt.toTimeZone(self.stationZone).toString('h:mm AP'))) self.tableWidget.setItem(i, 1, QTableWidgetItem(p['type'])) self.tableWidget.setItem( i, 2, QTableWidgetItem("{:.2f}".format(p['value']))) self.tableWidget.setRowHeight(i, 20) i += 1 self.tableWidget.setRowCount(i)
def __init__(self, iface, parent=None): super(GridExtractDialog, self).__init__(parent) # Set up the user interface from Designer. self.setupUi(self) self.iface = iface self.DISP_TEMP_LAYERS = read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS', bool) self.DEBUG = config.get_debug_mode() self.layers_df = None self.pixel_size = ['0', 'm', ''] # Catch and redirect python errors directed at the log messages python error tab. QgsApplication.messageLog().messageReceived.connect(errorCatcher) if not os.path.exists(TEMPDIR): os.mkdir(TEMPDIR) # Setup for validation messagebar on gui----------------------------- self.messageBar = QgsMessageBar( self) # leave this message bar for bailouts self.validationLayout = QtWidgets.QFormLayout( self) # new layout to gui if isinstance(self.layout(), QtWidgets.QFormLayout): # create a validation layout so multiple messages can be added and cleaned up. self.layout().insertRow(0, self.validationLayout) self.layout().insertRow(0, self.messageBar) else: self.layout().insertWidget( 0, self.messageBar) # for use with Vertical/horizontal layout box # GUI Runtime Customisation ----------------------------------------------- self.mcboPointsLayer.setFilters(QgsMapLayerProxyModel.PointLayer) self.mcboPointsLayer.setExcludedProviders(['wms']) self.mcboRasterLayer.setFilters(QgsMapLayerProxyModel.RasterLayer) self.mcboRasterLayer.setExcludedProviders(['wms']) self.setMapLayers() self.setWindowIcon( QtGui.QIcon(':/plugins/pat/icons/icon_gridExtract.svg')) self.chkgrpStatistics.setExclusive(False) self.tabList.setColumnCount(2) self.tabList.setHorizontalHeaderItem(0, QTableWidgetItem("ID")) self.tabList.setHorizontalHeaderItem(1, QTableWidgetItem("0 Raster(s)")) self.tabList.horizontalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) self.tabList.hideColumn(0) # don't need to display the unique layer ID self.pixel_size = ['0', 'm', ''] self.statsMapping = { 'mean': np.nanmean, 'minimum': np.nanmin, 'maximum': np.nanmax, 'standard deviation': np.nanstd, 'coefficient of variation': raster_ops.nancv, 'pixel count': raster_ops.pixelcount, }