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 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 _edit_trace_row(self, row, data): """Internal function to edit a row.""" for i, key in enumerate(self.config.layer_config['traces']['items']): cell = QTableWidgetItem() value = data.get(key) if not value: cell.setText('') cell.setData(Qt.UserRole, '') self.traces.setItem(row, i, cell) continue input_type = self.config.layer_config[key]['type'] if input_type == InputType.Field: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) # Get the icon for the field if self.layer: index = self.layer.currentLayer().fields().indexFromName( value) if index >= 0: cell.setIcon( self.layer.currentLayer().fields().iconForField( index)) elif input_type == InputType.Color: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) if value: cell.setData(Qt.DecorationRole, QColor(value)) else: raise Exception( 'InputType "{}" not implemented'.format(input_type)) self.traces.setItem(row, i, cell) self.traces.clearSelection()
def _edit_row(self, row, data): """Internal function to edit a row.""" self._layer = None for i, key in enumerate(data.keys()): value = data[key] cell = QTableWidgetItem() input_type = self.definitions.layer_config[key]['type'] if input_type == InputType.Layer: layer = QgsProject.instance().mapLayer(value) self._layer = layer cell.setText(layer.name()) cell.setData(Qt.UserRole, layer.id()) cell.setData( Qt.ToolTipRole, '{} ({})'.format(layer.name(), layer.crs().authid())) cell.setIcon(QgsMapLayerModel.iconForLayer(layer)) elif input_type == InputType.Field: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) # Get the icon for the field if self._layer: index = self._layer.fields().indexFromName(value) if index >= 0: cell.setIcon(self._layer.fields().iconForField(index)) elif input_type == InputType.Fields: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) elif input_type == InputType.Color: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) if value: cell.setData(Qt.DecorationRole, QColor(value)) elif input_type == InputType.CheckBox: if value: cell.setText('✓') cell.setData(Qt.UserRole, True) cell.setData(Qt.ToolTipRole, tr('True')) else: cell.setText('') cell.setData(Qt.UserRole, False) cell.setData(Qt.ToolTipRole, tr('False')) cell.setTextAlignment(Qt.AlignCenter) elif input_type == InputType.List: cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) items = self.definitions.layer_config[key].get('items') if items: for item_enum in items: if item_enum.value['data'] == value: text = item_enum.value['label'] icon = item_enum.value.get('icon') break else: raise Exception( 'Error with list value="{}"'.format(value)) cell.setText(text) if icon: cell.setIcon(QIcon(icon)) else: cell.setText(value) elif input_type == InputType.SpinBox: cell.setText(str(value)) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) elif input_type == InputType.Text: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) else: raise Exception( 'InputType "{}" not implemented'.format(input_type)) self.table.setItem(row, i, cell) self._layer = None self.table.clearSelection()
def _edit_row(self, row, data): """Internal function to edit a row.""" self._layer = None for i, key in enumerate(data.keys()): value = data[key] cell = QTableWidgetItem() input_type = self.definitions.layer_config[key]['type'] if self._layer and hasattr(value, '__call__'): # Value is a for now a function, we need to evaluate it value = value(self._layer) if input_type == InputType.Layer: layer = QgsProject.instance().mapLayer(value) self._layer = layer cell.setText(layer.name()) cell.setData(Qt.UserRole, layer.id()) cell.setData( Qt.ToolTipRole, '{} ({})'.format(layer.name(), layer.crs().authid())) cell.setIcon(QgsMapLayerModel.iconForLayer(layer)) elif input_type == InputType.Layers: names = [] for layer in value: if layer != '': vector = QgsProject.instance().mapLayer(layer) if vector: names.append(vector.name()) display = ' ,'.join(names) cell.setText(display) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, display) elif input_type == InputType.Field: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) # Get the icon for the field if self._layer: index = self._layer.fields().indexFromName(value) if index >= 0: cell.setIcon(self._layer.fields().iconForField(index)) elif input_type == InputType.Fields: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) elif input_type == InputType.Color: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) if value: cell.setData(Qt.DecorationRole, QColor(value)) elif input_type == InputType.CheckBox: if value: cell.setText('✓') cell.setData(Qt.UserRole, True) cell.setData(Qt.ToolTipRole, tr('True')) else: cell.setText('') cell.setData(Qt.UserRole, False) cell.setData(Qt.ToolTipRole, tr('False')) cell.setTextAlignment(Qt.AlignCenter) elif input_type == InputType.Json: if value: cell.setText(json.dumps(value)) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) else: cell.setText('') cell.setData(Qt.UserRole, '') cell.setData(Qt.ToolTipRole, '') elif input_type == InputType.List: cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) items = self.definitions.layer_config[key].get('items') if items: for item_enum in items: if item_enum.value['data'] == value: text = item_enum.value['label'] icon = item_enum.value.get('icon') break else: msg = 'Error with value = "{}" in list "{}"'.format( value, key) LOGGER.critical(msg) raise Exception(msg) cell.setText(text) if icon: cell.setIcon(QIcon(icon)) else: cell.setText(value) elif input_type == InputType.SpinBox: unit = self.definitions.layer_config[key].get('unit') if unit: display = '{}{}'.format(value, unit) else: display = '{}'.format(value) cell.setText(display) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) elif input_type == InputType.Text: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) elif input_type == InputType.MultiLine: cell.setText(value) cell.setData(Qt.UserRole, value) cell.setData(Qt.ToolTipRole, value) elif input_type == InputType.Collection: json_dump = json.dumps(value) cell.setText(json_dump) cell.setData(Qt.UserRole, value) function = self.definitions.layer_config[key][ 'represent_value'] cell.setData(Qt.ToolTipRole, function(value)) else: raise Exception( 'InputType "{}" not implemented'.format(input_type)) self.table.setItem(row, i, cell) self._layer = None self.table.clearSelection()
def populateLayerTable(self, layerType): """ Fill the table for a given layer type """ # Get parameters for the widget lt = self.layersTable[layerType] table = lt['tableWidget'] # Reset layerBoardChangedData self.layerBoardChangedData[layerType] = {} # disconnect itemChanged signal try: table.itemChanged.disconnect() except Exception: pass attributes = self.layersTable['generic']['attributes'] + lt['attributes'] self.layersAttributes[layerType] = attributes self.layerBoardData[layerType] = [] headerData = [a['key'] for a in attributes] self.layerBoardData[layerType].append(headerData) # empty previous content for row in range(table.rowCount()): table.removeRow(row) table.setRowCount(0) table.setColumnCount(0) # create columns and header row columns = [a['key'] for a in attributes] columnsLabels = [a['label'] for a in attributes] colCount = len(columns) table.setColumnCount(colCount) table.setHorizontalHeaderLabels(tuple(columnsLabels)) # load content from project layers lr = QgsProject().instance() for lid in lr.mapLayers(): layer = lr.mapLayer(lid) if layerType == 'vector' and layer.type() != QgsMapLayer.VectorLayer: continue if layerType == 'raster' and layer.type() != QgsMapLayer.RasterLayer: continue # Add layer in the layerBoardChangedData self.layerBoardChangedData[layerType][lid] = {} lineData = [] # Set row and column count twRowCount = table.rowCount() # add a new line table.setRowCount(twRowCount + 1) table.setColumnCount(colCount) i = 0 # get information for attr in attributes: newItem = QTableWidgetItem() newItem.setToolTip(layer.name()) if layerType == 'vector' and not layer.isSpatial() and attr.get('spatial_only'): newItem.setFlags(Qt.NoItemFlags) # Is editable or not elif attr.get('editable'): newItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled) else: newItem.setFlags(Qt.ItemIsSelectable) # Item value if layerType == 'vector' and not layer.isSpatial() and attr.get('spatial_only'): value = None else: value = self.getLayerProperty(layer, attr['key']) newItem.setData(Qt.EditRole, value) # Add cell data to lineData # encode it in the file system encoding, only if needed # TODO DISABLED due to migration to Python 3, related to CSV export # if hasattr(value, 'encode'): # value = value.encode(sys.getfilesystemencoding()) lineData.append(value) if attr['key'] == 'name': icon = QgsMapLayerModel.iconForLayer(layer) newItem.setIcon(icon) # Add item table.setItem(twRowCount, i, newItem) i += 1 # Add data to layerBoardData self.layerBoardData[layerType].append(lineData) # Launch slot on item changed slot slot = partial(self.onItemChanged, layerType) table.itemChanged.connect(slot)
def create_table(self): from AcATaMa.gui.acatama_dockwidget import AcATaMaDockWidget as AcATaMa header = ["Classification Name", "Color", "Thematic Class", ""] # clear table self.tableBtnsConfig.clear() # init table self.tableBtnsConfig.setRowCount(len(self.table_buttons)) self.tableBtnsConfig.setColumnCount(4) # hidden row labels self.tableBtnsConfig.verticalHeader().setVisible(False) # add Header self.tableBtnsConfig.setHorizontalHeaderLabels(header) # insert items for n, h in enumerate(header): if h == "Classification Name": for m, (key, item) in enumerate(self.table_buttons.items()): if m + 1 in self.buttons_config: item_table = QTableWidgetItem( self.buttons_config[m + 1]["name"]) else: item_table = QTableWidgetItem(str(item)) item_table.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter) item_table.setToolTip( "Classification button ID: {}".format(key)) self.tableBtnsConfig.setItem(m, n, item_table) if h == "Color": for m, item in enumerate(self.table_buttons.values()): item_table = QTableWidgetItem() if m + 1 in self.buttons_config: item_table.setBackground( QColor(self.buttons_config[m + 1]["color"])) item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) item_table.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter) self.tableBtnsConfig.setItem(m, n, item_table) if h == "Thematic Class": for m, item in enumerate(self.table_buttons.values()): if valid_file_selected_in( AcATaMa.dockwidget.QCBox_ThematicRaster): if m + 1 in self.buttons_config and self.buttons_config[ m + 1]["thematic_class"] is not None: item_table = QTableWidgetItem( self.buttons_config[m + 1]["thematic_class"]) else: item_table = QTableWidgetItem(str(item)) item_table.setToolTip( "Click to open the pixel value/color table of the thematic classes" ) else: item_table = QTableWidgetItem("none") item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) item_table.setForeground(QColor("lightGrey")) item_table.setToolTip( "No thematic layer, if you want enable the thematic classes,\n" "select first a valid thematic layer in thematic tab" ) item_h = QTableWidgetItem(h) item_h.setForeground(QColor("lightGrey")) self.tableBtnsConfig.setHorizontalHeaderItem(2, item_h) item_table.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter) self.tableBtnsConfig.setItem(m, n, item_table) if h == "": for m, item in enumerate(self.table_buttons.values()): item_table = QTableWidgetItem() path = ':/plugins/AcATaMa/icons/trash.svg' icon = QIcon(path) item_table.setIcon(icon) item_table.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) item_table.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter) item_table.setToolTip("Clean this row") self.tableBtnsConfig.setItem(m, n, item_table) # set the minimum width to 0 for headers self.tableBtnsConfig.horizontalHeader().setMinimumSectionSize(0) # adjust size of Table self.tableBtnsConfig.resizeColumnsToContents() self.tableBtnsConfig.resizeRowsToContents() # adjust the dialog based on table content dialog_width = self.tableBtnsConfig.horizontalHeader().length() + 50 self.resize(dialog_width, self.height())