def populate_details(self): self.imgWidgets = [] layout = QGridLayout() layout.setMargin(0) layout.setVerticalSpacing(15) layout.setColumnStretch(0, 1) layout.setColumnStretch(2, 1) self.chkClip = None self.chkHarmonize = None if self.add_clip: layout.addWidget(QLabel("<b>Clipping</b>"), 0, 1, Qt.AlignCenter) layout.addWidget( QLabel("Only get items delivered within your AOI"), 1, 1, Qt.AlignCenter) self.chkClip = QCheckBox("Clip items to AOI") enabled = QSettings().value( f"{SETTINGS_NAMESPACE}/{ENABLE_CLIP_SETTING}", False) self.chkClip.setChecked(str(enabled).lower() == str(True).lower()) self.chkClip.stateChanged.connect(self.checkStateChanged) layout.addWidget(self.chkClip, 2, 1, Qt.AlignCenter) if self.add_harmonize: layout.addWidget(QLabel("<b>Harmonization</b>"), 3, 1, Qt.AlignCenter) layout.addWidget( QLabel( "Radiometrically harmonize imagery captured by one satellite " "instrument type to imagery capture by another"), 4, 1, Qt.AlignCenter, ) self.chkHarmonize = QCheckBox("Harmonize") enabled = QSettings().value( f"{SETTINGS_NAMESPACE}/{ENABLE_HARMONIZATION_SETTING}", False) self.chkHarmonize.setChecked( str(enabled).lower() == str(True).lower()) self.chkHarmonize.stateChanged.connect(self.checkStateChanged) layout.addWidget(self.chkHarmonize, 5, 1, Qt.AlignCenter) layout.addWidget(QLabel("<b>Review Items</b>"), 6, 1, Qt.AlignCenter) layout.addWidget( QLabel( "We recommend deselecting items that appear to have no pixels" ), 7, 1, Qt.AlignCenter, ) sublayout = QGridLayout() sublayout.setMargin(0) for i, img in enumerate(self.images): w = ImageReviewWidget(img) w.selectedChanged.connect(self.selectedImagesChanged.emit) row = i // 4 col = i % 4 + 1 sublayout.addWidget(w, row, col) self.imgWidgets.append(w) layout.addLayout(sublayout, 8, 1, Qt.AlignCenter) self.widgetDetails.setLayout(layout)
def populate_details(self): self.imgWidgets = [] layout = QGridLayout() layout.setMargin(0) layout.setVerticalSpacing(15) layout.setColumnStretch(0, 1) layout.setColumnStretch(2, 1) self.chkClip = None if self.add_clip: layout.addWidget(QLabel("<b>Clipping</b>"), 0, 1, Qt.AlignCenter) layout.addWidget( QLabel("Only get items delivered within your AOI"), 1, 1, Qt.AlignCenter) self.chkClip = QCheckBox("Clip items to AOI") self.chkClip.stateChanged.connect(self.checkStateChanged) layout.addWidget(self.chkClip, 2, 1, Qt.AlignCenter) layout.addWidget(QLabel("<b>Review Items</b>"), 3, 1, Qt.AlignCenter) layout.addWidget( QLabel( "We recommend deselecting items that appear to have no pixels" ), 4, 1, Qt.AlignCenter) sublayout = QGridLayout() sublayout.setMargin(0) for i, img in enumerate(self.images): w = ImageReviewWidget(img) w.selectedChanged.connect(self.selectedImagesChanged.emit) row = i // 4 col = i % 4 + 1 sublayout.addWidget(w, row, col) self.imgWidgets.append(w) layout.addLayout(sublayout, 5, 1, Qt.AlignCenter) self.widgetDetails.setLayout(layout)
def createWidgets(self): glayout = QGridLayout() vlayout = QVBoxLayout() self._list = TableDataSelectionWidget() self.regProp("dest_data", WizProp(self._list, [])) radio = QRadioButton("Weigh attractions equally") radio.setChecked(True) vlayout.addWidget(radio) radio = WidgetEnableRadioButton("Weigh attractions by data", [self._list]) self.regProp("dest_data_enabled", WizProp(radio, False)) vlayout.addWidget(radio) vlayout.addWidget(self._list) glayout.addLayout(vlayout, 0, 0) vlayout = QVBoxLayout() vlayout.addWidget(QLabel("Attraction name (for output column)")) edit = QLineEdit() self.regProp("dest_name", WizProp(edit, "")) vlayout.addWidget(edit) vlayout.addStretch() glayout.addLayout(vlayout, 0, 1) self.setLayout(glayout)
def createWidgets(self): glayout = QGridLayout() vlayout = QVBoxLayout() self._list = TableDataSelectionWidget() self.regProp("dest_data", WizProp(self._list, [])) vlayout.addWidget(QLabel("Find minimum distance to:")) radio = QRadioButton("Any destination element") radio.setChecked(True) vlayout.addWidget(radio) radio = WidgetEnableRadioButton( "Destination element with specific attractions", [self._list]) self.regProp("dest_data_enabled", WizProp(radio, False)) vlayout.addWidget(radio) vlayout.addWidget(self._list) glayout.addLayout(vlayout, 0, 0) vlayout = QVBoxLayout() vlayout.addWidget(QLabel("Destination name (for output column)")) edit = QLineEdit() self.regProp("dest_name", WizProp(edit, "")) vlayout.addWidget(edit) vlayout.addStretch() glayout.addLayout(vlayout, 0, 1) self.setLayout(glayout)
class DefaultSelectParameterWidget(SelectParameterWidget): """Widget class for Default Select Parameter.""" def __init__(self, parameter, parent=None): """Constructor :param parameter: A DefaultSelectParameter object. :type parameter: DefaultSelectParameter """ super(DefaultSelectParameterWidget, self).__init__(parameter, parent) self.default_layout = QHBoxLayout() self.radio_button_layout = QHBoxLayout() self.radio_button_widget = QWidget() self.default_label = QLabel(tr('Default')) # Create radio button group self.default_input_button_group = QButtonGroup() # Define string enabler for radio button self.radio_button_enabler = self.input.itemData(0, Qt.UserRole) for i in range(len(self._parameter.default_labels)): if '%s' in self._parameter.default_labels[i]: label = ( self._parameter.default_labels[i] % self._parameter.default_values[i]) else: label = self._parameter.default_labels[i] radio_button = QRadioButton(label) self.radio_button_layout.addWidget(radio_button) self.default_input_button_group.addButton(radio_button, i) if self._parameter.default_value == \ self._parameter.default_values[i]: radio_button.setChecked(True) # Create double spin box for custom value self.custom_value = QDoubleSpinBox() if self._parameter.default_values[-1]: self.custom_value.setValue(self._parameter.default_values[-1]) has_min = False if self._parameter.minimum is not None: has_min = True self.custom_value.setMinimum(self._parameter.minimum) has_max = False if self._parameter.maximum is not None: has_max = True self.custom_value.setMaximum(self._parameter.maximum) if has_min and has_max: step = (self._parameter.maximum - self._parameter.minimum) / 100.0 self.custom_value.setSingleStep(step) self.radio_button_layout.addWidget(self.custom_value) self.toggle_custom_value() # Reset the layout self.input_layout.setParent(None) self.help_layout.setParent(None) self.label.setParent(None) self.inner_input_layout.setParent(None) self.input_layout = QGridLayout() self.input_layout.setSpacing(0) self.input_layout.addWidget(self.label, 0, 0) self.input_layout.addLayout(self.inner_input_layout, 0, 1) self.input_layout.addWidget(self.default_label, 1, 0) self.input_layout.addLayout(self.radio_button_layout, 1, 1) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) # check every added combobox, it could have been toggled by # the existing keyword self.toggle_input() # Connect # noinspection PyUnresolvedReferences self.input.currentIndexChanged.connect(self.toggle_input) self.default_input_button_group.buttonClicked.connect( self.toggle_custom_value) def raise_invalid_type_exception(self): message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) err = ValueError(message) return err def get_parameter(self): """Obtain list parameter object from the current widget state. :returns: A DefaultSelectParameter from the current state of widget. """ current_index = self.input.currentIndex() selected_value = self.input.itemData(current_index, Qt.UserRole) if hasattr(selected_value, 'toPyObject'): selected_value = selected_value.toPyObject() try: self._parameter.value = selected_value except ValueError: err = self.raise_invalid_type_exception() raise err radio_button_checked_id = self.default_input_button_group.checkedId() # No radio button checked, then default value = None if radio_button_checked_id == -1: self._parameter.default = None # The last radio button (custom) is checked, get the value from the # line edit elif (radio_button_checked_id == len(self._parameter.default_values) - 1): self._parameter.default_values[radio_button_checked_id] \ = self.custom_value.value() self._parameter.default = self.custom_value.value() else: self._parameter.default = self._parameter.default_values[ radio_button_checked_id] return self._parameter def set_default(self, default): """Set default value by item's string. :param default: The default. :type default: str, int :returns: True if success, else False. :rtype: bool """ # Find index of choice try: default_index = self._parameter.default_values.index(default) self.default_input_button_group.button(default_index).setChecked( True) except ValueError: last_index = len(self._parameter.default_values) - 1 self.default_input_button_group.button(last_index).setChecked( True) self.custom_value.setValue(default) self.toggle_custom_value() def toggle_custom_value(self): radio_button_checked_id = self.default_input_button_group.checkedId() if (radio_button_checked_id == len(self._parameter.default_values) - 1): self.custom_value.setDisabled(False) else: self.custom_value.setDisabled(True) def toggle_input(self): """Change behaviour of radio button based on input.""" current_index = self.input.currentIndex() # If current input is not a radio button enabler, disable radio button. if self.input.itemData(current_index, Qt.UserRole) != ( self.radio_button_enabler): self.disable_radio_button() # Otherwise, enable radio button. else: self.enable_radio_button() def set_selected_radio_button(self): """Set selected radio button to 'Do not report'.""" dont_use_button = self.default_input_button_group.button( len(self._parameter.default_values) - 2) dont_use_button.setChecked(True) def disable_radio_button(self): """Disable radio button group and custom value input area.""" checked = self.default_input_button_group.checkedButton() if checked: self.default_input_button_group.setExclusive(False) checked.setChecked(False) self.default_input_button_group.setExclusive(True) for button in self.default_input_button_group.buttons(): button.setDisabled(True) self.custom_value.setDisabled(True) def enable_radio_button(self): """Enable radio button and custom value input area then set selected radio button to 'Do not report'. """ for button in self.default_input_button_group.buttons(): button.setEnabled(True) self.set_selected_radio_button() self.custom_value.setEnabled(True)
def setup_thresholds_panel(self, classification): """Setup threshold panel in the right panel. :param classification: Classification definition. :type classification: dict """ # Set text in the label layer_purpose = self.parent.step_kw_purpose.selected_purpose() layer_subcategory = self.parent.step_kw_subcategory.\ selected_subcategory() if is_raster_layer(self.parent.layer): active_band = self.parent.step_kw_band_selector.selected_band() layer_extent = self.parent.layer.extent() statistics = self.parent.layer.dataProvider().bandStatistics( active_band, QgsRasterBandStats.All, layer_extent, 0) description_text = continuous_raster_question % ( layer_purpose['name'], layer_subcategory['name'], classification['name'], statistics.minimumValue, statistics.maximumValue) else: field_name = self.parent.step_kw_field.selected_fields() field_index = self.parent.layer.fields().lookupField(field_name) min_value_layer = self.parent.layer.minimumValue(field_index) max_value_layer = self.parent.layer.maximumValue(field_index) description_text = continuous_vector_question % ( layer_purpose['name'], layer_subcategory['name'], field_name, classification['name'], min_value_layer, max_value_layer) # Set description description_label = QLabel(description_text) description_label.setWordWrap(True) self.right_layout.addWidget(description_label) if self.thresholds: thresholds = self.thresholds else: thresholds = self.parent.get_existing_keyword('thresholds') selected_unit = self.parent.step_kw_unit.selected_unit()['key'] self.threshold_classes = OrderedDict() classes = classification.get('classes') # Sort by value, put the lowest first classes = sorted(classes, key=lambda the_key: the_key['value']) grid_layout_thresholds = QGridLayout() for i, the_class in enumerate(classes): class_layout = QHBoxLayout() # Class label class_label = QLabel(the_class['name']) # Min label min_label = QLabel(tr('Min >')) # Min value as double spin min_value_input = QDoubleSpinBox() # TODO(IS) We can set the min and max depends on the unit, later min_value_input.setMinimum(0) min_value_input.setMaximum(999999) if thresholds.get(self.active_exposure['key']): exposure_thresholds = thresholds.get( self.active_exposure['key']) if exposure_thresholds.get(classification['key']): exposure_thresholds_classifications = exposure_thresholds\ .get(classification['key']) min_value_input.setValue( exposure_thresholds_classifications['classes'][ the_class['key']][0]) else: default_min = the_class['numeric_default_min'] if isinstance(default_min, dict): default_min = the_class[ 'numeric_default_min'][selected_unit] min_value_input.setValue(default_min) else: default_min = the_class['numeric_default_min'] if isinstance(default_min, dict): default_min = the_class[ 'numeric_default_min'][selected_unit] min_value_input.setValue(default_min) min_value_input.setSingleStep(0.1) # Max label max_label = QLabel(tr('Max <=')) # Max value as double spin max_value_input = QDoubleSpinBox() # TODO(IS) We can set the min and max depends on the unit, later max_value_input.setMinimum(0) max_value_input.setMaximum(999999) if thresholds.get(self.active_exposure['key']): exposure_thresholds = thresholds.get( self.active_exposure['key']) if exposure_thresholds.get(classification['key']): exposure_thresholds_classifications = exposure_thresholds \ .get(classification['key']) max_value_input.setValue( exposure_thresholds_classifications['classes'][ the_class['key']][1]) else: default_max = the_class['numeric_default_max'] if isinstance(default_max, dict): default_max = the_class[ 'numeric_default_max'][selected_unit] max_value_input.setValue(default_max) else: default_max = the_class['numeric_default_max'] if isinstance(default_max, dict): default_max = the_class[ 'numeric_default_max'][selected_unit] max_value_input.setValue(default_max) max_value_input.setSingleStep(0.1) # Add to class_layout class_layout.addWidget(min_label) class_layout.addWidget(min_value_input) class_layout.addWidget(max_label) class_layout.addWidget(max_value_input) class_layout.setStretch(0, 1) class_layout.setStretch(1, 2) class_layout.setStretch(2, 1) class_layout.setStretch(3, 2) # Add to grid_layout grid_layout_thresholds.addWidget(class_label, i, 0) grid_layout_thresholds.addLayout(class_layout, i, 1) self.threshold_classes[the_class['key']] = [ min_value_input, max_value_input] grid_layout_thresholds.setColumnStretch(0, 1) grid_layout_thresholds.setColumnStretch(0, 2) def min_max_changed(double_spin_index, mode): """Slot when min or max value change. :param double_spin_index: The index of the double spin. :type double_spin_index: int :param mode: The flag to indicate the min or max value. :type mode: int """ if mode == MAX_VALUE_MODE: current_max_value = list(self.threshold_classes.values())[ double_spin_index][1] target_min_value = list(self.threshold_classes.values())[ double_spin_index + 1][0] if current_max_value.value() != target_min_value.value(): target_min_value.setValue(current_max_value.value()) elif mode == MIN_VALUE_MODE: current_min_value = list(self.threshold_classes.values())[ double_spin_index][0] target_max_value = list(self.threshold_classes.values())[ double_spin_index - 1][1] if current_min_value.value() != target_max_value.value(): target_max_value.setValue(current_min_value.value()) # Set behaviour for k, v in list(self.threshold_classes.items()): index = list(self.threshold_classes.keys()).index(k) if index < len(self.threshold_classes) - 1: # Max value changed v[1].valueChanged.connect(partial( min_max_changed, double_spin_index=index, mode=MAX_VALUE_MODE)) if index > 0: # Min value v[0].valueChanged.connect(partial( min_max_changed, double_spin_index=index, mode=MIN_VALUE_MODE)) grid_layout_thresholds.setSpacing(0) self.right_layout.addLayout(grid_layout_thresholds)
class AdvancedSearch(EntityEditorDialog): search_triggered = pyqtSignal(dict) def __init__(self, entity, parent, initial_values: dict = None): super().__init__(entity, parent=parent) self.parent = parent self.initial_values = initial_values or {} for k, v in self.initial_values.items(): for mapper in self._attrMappers: if mapper.attributeName() == k: mapper.valueHandler().setValue(v) def _init_gui(self, show_str_tab: bool, is_party_unit: bool=False): # Setup base elements self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName('glMain') self.gridLayout.addLayout( self.vlNotification, 0, 0, 1, 1 ) column_widget_area = self._setup_columns_content_area() self.gridLayout.addWidget( column_widget_area, 1, 0, 1, 1 ) # Add notification for mandatory columns if applicable next_row = 2 # Set title search_trans = self.tr('Advanced Search') if self._entity.label is not None: if self._entity.label != '': title_str = self._entity.label else: title_str = format_name(self._entity.short_name) else: title_str = format_name(self._entity.short_name) title = '{0} {1}'.format(title_str, search_trans) self.do_not_check_dirty = True self.setWindowTitle(title) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setObjectName('buttonBox') self.gridLayout.addWidget( self.buttonBox, next_row, 0, 1, 1 ) self.buttonBox.setOrientation(Qt.Horizontal) self.search = QPushButton( QApplication.translate( 'EntityEditorDialog', 'Search' ) ) self.buttonBox.addButton( self.search, QDialogButtonBox.ActionRole ) self.buttonBox.setStandardButtons( QDialogButtonBox.Close | QDialogButtonBox.Reset ) self.search.clicked.connect(self.on_search) self.buttonBox.button(QDialogButtonBox.Close).clicked.connect(self.reject) self.buttonBox.button(QDialogButtonBox.Reset).clicked.connect(self.reset) def reset(self): """ Resets the dialog back to an empty/no filter status """ for column in self._entity.columns.values(): if column.name in entity_display_columns(self._entity): if column.name == 'id': continue handler = self.attribute_mappers[ column.name].valueHandler() handler.setValue(handler.default()) def on_search(self): """ Builds a dictionary of the desired search values and emits the search_triggered signal """ self.search_triggered.emit(self.current_search_data()) def current_search_data(self) -> dict: """ Returns a dictionary representing the current search data """ search_data = {} for column in self._entity.columns.values(): if column.name in entity_display_columns(self._entity): if column.name == 'id': continue handler = self.attribute_mappers[ column.name].valueHandler() value = handler.value() if value != handler.default() and bool(value): search_data[column.name] = value return search_data def _setup_columns_content_area(self): # Only use this if entity supports documents # self.entity_tab_widget = None self.doc_widget = None self.entity_scroll_area = QScrollArea(self) self.entity_scroll_area.setFrameShape(QFrame.NoFrame) self.entity_scroll_area.setWidgetResizable(True) self.entity_scroll_area.setObjectName('scrollArea') # Grid layout for controls self.gl = QGridLayout(self.scroll_widget_contents) self.gl.setObjectName('gl_widget_contents') # Append column labels and widgets table_name = self._entity.name columns = table_column_names(table_name) # Iterate entity column and assert if they exist row_id = 0 for column_name, column_widget in self.column_widgets.items(): c = self.columns[column_name] if c.name in self.exclude_columns: continue if isinstance(c, MultipleSelectColumn): continue if c.name not in columns and not isinstance(c, VirtualColumn): continue if column_widget is not None: header = c.ui_display() self.c_label = QLabel(self.scroll_widget_contents) self.c_label.setText(header) self.gl.addWidget(self.c_label, row_id, 0, 1, 1) if c.TYPE_INFO == 'AUTO_GENERATED': column_widget.setReadOnly(False) column_widget.btn_load.hide() self.gl.addWidget(column_widget, row_id, 1, 1, 1) col_name = c.name # Add widget to MapperMixin collection self.addMapping( col_name, column_widget, c.mandatory, pseudoname=c.ui_display() ) # Bump up row_id row_id += 1 self.entity_scroll_area.setWidget(self.scroll_widget_contents) if self.entity_tab_widget is None: self.entity_tab_widget = QTabWidget(self) # Check if there are children and add foreign key browsers # Add primary tab if necessary self._add_primary_attr_widget() # self.entity_tab_widget.setTabEnabled(0, False) # enable/disable the tab # set the style sheet self.setStyleSheet( "QTabBar::tab::selected {width: 0; height: 0; margin: 0; " "padding: 0; border: none;} ") # Return the correct widget if self.entity_tab_widget is not None: return self.entity_tab_widget return self.entity_scroll_area
class Ui_DistroMap(object): def setupUi(self, DistroMap): DistroMap.setObjectName("DistroMap") DistroMap.resize(439, 657) self.gridLayout_3 = QGridLayout(DistroMap) self.gridLayout_3.setObjectName("gridLayout_3") self.scrollArea = QScrollArea(DistroMap) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 419, 573)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.gridLayout_6 = QGridLayout(self.scrollAreaWidgetContents) self.gridLayout_6.setObjectName("gridLayout_6") self.verticalLayout = QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.label_5 = QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName("label_5") self.verticalLayout.addWidget(self.label_5) self.comboLocalities = QComboBox(self.scrollAreaWidgetContents) self.comboLocalities.setObjectName("comboLocalities") self.verticalLayout.addWidget(self.comboLocalities) self.gridLayout_6.addLayout(self.verticalLayout, 1, 0, 1, 1) self.horizontalLayout_6 = QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.verticalLayout_13 = QVBoxLayout() self.verticalLayout_13.setObjectName("verticalLayout_13") self.label_19 = QLabel(self.scrollAreaWidgetContents) self.label_19.setObjectName("label_19") self.verticalLayout_13.addWidget(self.label_19) self.horizontalLayout_3 = QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.spnOutWidth = QSpinBox(self.scrollAreaWidgetContents) self.spnOutWidth.setMaximum(999999) self.spnOutWidth.setProperty("value", 325) self.spnOutWidth.setObjectName("spnOutWidth") self.horizontalLayout_3.addWidget(self.spnOutWidth) self.label_20 = QLabel(self.scrollAreaWidgetContents) self.label_20.setAlignment(Qt.AlignCenter) self.label_20.setObjectName("label_20") self.horizontalLayout_3.addWidget(self.label_20) self.spnOutHeight = QSpinBox(self.scrollAreaWidgetContents) self.spnOutHeight.setMaximum(999999) self.spnOutHeight.setProperty("value", 299) self.spnOutHeight.setObjectName("spnOutHeight") self.horizontalLayout_3.addWidget(self.spnOutHeight) self.verticalLayout_13.addLayout(self.horizontalLayout_3) self.horizontalLayout_6.addLayout(self.verticalLayout_13) self.horizontalLayout_5 = QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.verticalLayout_14 = QVBoxLayout() self.verticalLayout_14.setObjectName("verticalLayout_14") self.label_21 = QLabel(self.scrollAreaWidgetContents) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label_21.sizePolicy().hasHeightForWidth()) self.label_21.setSizePolicy(sizePolicy) self.label_21.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.label_21.setObjectName("label_21") self.verticalLayout_14.addWidget(self.label_21) self.horizontalLayout_4 = QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem) self.btnColour = QPushButton(self.scrollAreaWidgetContents) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnColour.sizePolicy().hasHeightForWidth()) self.btnColour.setSizePolicy(sizePolicy) self.btnColour.setObjectName("btnColour") self.horizontalLayout_4.addWidget(self.btnColour) self.verticalLayout_14.addLayout(self.horizontalLayout_4) self.horizontalLayout_5.addLayout(self.verticalLayout_14) self.frmColour = QFrame(self.scrollAreaWidgetContents) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frmColour.sizePolicy().hasHeightForWidth()) self.frmColour.setSizePolicy(sizePolicy) self.frmColour.setMinimumSize(QSize(45, 45)) self.frmColour.setSizeIncrement(QSize(1, 1)) self.frmColour.setBaseSize(QSize(0, 0)) self.frmColour.setFrameShape(QFrame.StyledPanel) self.frmColour.setFrameShadow(QFrame.Raised) self.frmColour.setObjectName("frmColour") self.horizontalLayout_5.addWidget(self.frmColour) self.horizontalLayout_6.addLayout(self.horizontalLayout_5) self.gridLayout_6.addLayout(self.horizontalLayout_6, 4, 0, 1, 1) self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.label_6 = QLabel(self.scrollAreaWidgetContents) self.label_6.setObjectName("label_6") self.verticalLayout_2.addWidget(self.label_6) self.comboTaxonField = QComboBox(self.scrollAreaWidgetContents) self.comboTaxonField.setObjectName("comboTaxonField") self.verticalLayout_2.addWidget(self.comboTaxonField) self.gridLayout_6.addLayout(self.verticalLayout_2, 2, 0, 1, 1) self.verticalLayout_5 = QVBoxLayout() self.verticalLayout_5.setObjectName("verticalLayout_5") self.label_9 = QLabel(self.scrollAreaWidgetContents) self.label_9.setObjectName("label_9") self.verticalLayout_5.addWidget(self.label_9) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.leOutDir = QLineEdit(self.scrollAreaWidgetContents) self.leOutDir.setPlaceholderText("") self.leOutDir.setObjectName("leOutDir") self.horizontalLayout.addWidget(self.leOutDir) self.btnBrowse = QPushButton(self.scrollAreaWidgetContents) self.btnBrowse.setObjectName("btnBrowse") self.horizontalLayout.addWidget(self.btnBrowse) self.verticalLayout_5.addLayout(self.horizontalLayout) self.gridLayout_6.addLayout(self.verticalLayout_5, 5, 0, 1, 1) self.verticalLayout_6 = QVBoxLayout() self.verticalLayout_6.setObjectName("verticalLayout_6") self.label = QLabel(self.scrollAreaWidgetContents) self.label.setObjectName("label") self.verticalLayout_6.addWidget(self.label) self.gridLayout = QGridLayout() self.gridLayout.setObjectName("gridLayout") self.label_2 = QLabel(self.scrollAreaWidgetContents) self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1) self.comboSecondary = QComboBox(self.scrollAreaWidgetContents) self.comboSecondary.setObjectName("comboSecondary") self.gridLayout.addWidget(self.comboSecondary, 1, 1, 1, 1) self.comboSurface = QComboBox(self.scrollAreaWidgetContents) self.comboSurface.setObjectName("comboSurface") self.gridLayout.addWidget(self.comboSurface, 2, 1, 1, 1) self.label_3 = QLabel(self.scrollAreaWidgetContents) self.label_3.setObjectName("label_3") self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1) self.label_4 = QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName("label_4") self.gridLayout.addWidget(self.label_4, 2, 0, 1, 1) self.comboBase = QComboBox(self.scrollAreaWidgetContents) self.comboBase.setObjectName("comboBase") self.gridLayout.addWidget(self.comboBase, 0, 1, 1, 1) self.gridLayout.setColumnStretch(0, 1) self.gridLayout.setColumnStretch(1, 3) self.verticalLayout_6.addLayout(self.gridLayout) self.gridLayout_6.addLayout(self.verticalLayout_6, 0, 0, 1, 1) self.verticalLayout_3 = QVBoxLayout() self.verticalLayout_3.setObjectName("verticalLayout_3") self.label_7 = QLabel(self.scrollAreaWidgetContents) self.label_7.setObjectName("label_7") self.verticalLayout_3.addWidget(self.label_7) self.comboGrid = QComboBox(self.scrollAreaWidgetContents) self.comboGrid.setObjectName("comboGrid") self.verticalLayout_3.addWidget(self.comboGrid) self.verticalLayout_4 = QVBoxLayout() self.verticalLayout_4.setObjectName("verticalLayout_4") self.label_8 = QLabel(self.scrollAreaWidgetContents) self.label_8.setObjectName("label_8") self.verticalLayout_4.addWidget(self.label_8) self.gridLayout_2 = QGridLayout() self.gridLayout_2.setObjectName("gridLayout_2") self.leMaxY = QLineEdit(self.scrollAreaWidgetContents) self.leMaxY.setObjectName("leMaxY") self.gridLayout_2.addWidget(self.leMaxY, 0, 1, 1, 1) self.leMinX = QLineEdit(self.scrollAreaWidgetContents) self.leMinX.setObjectName("leMinX") self.gridLayout_2.addWidget(self.leMinX, 1, 0, 1, 1) self.leMaxX = QLineEdit(self.scrollAreaWidgetContents) self.leMaxX.setObjectName("leMaxX") self.gridLayout_2.addWidget(self.leMaxX, 1, 2, 1, 1) self.leMinY = QLineEdit(self.scrollAreaWidgetContents) self.leMinY.setObjectName("leMinY") self.gridLayout_2.addWidget(self.leMinY, 2, 1, 1, 1) self.btnExtent = QPushButton(self.scrollAreaWidgetContents) self.btnExtent.setObjectName("btnExtent") self.gridLayout_2.addWidget(self.btnExtent, 1, 1, 1, 1) self.verticalLayout_4.addLayout(self.gridLayout_2) self.verticalLayout_3.addLayout(self.verticalLayout_4) self.gridLayout_6.addLayout(self.verticalLayout_3, 3, 0, 1, 1) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.gridLayout_3.addWidget(self.scrollArea, 0, 0, 1, 1) self.buttonBox = QDialogButtonBox(DistroMap) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.gridLayout_3.addWidget(self.buttonBox, 2, 0, 1, 1) self.progressBar = QProgressBar(DistroMap) self.progressBar.setProperty("value", 0) self.progressBar.setObjectName("progressBar") self.gridLayout_3.addWidget(self.progressBar, 1, 0, 1, 1) self.retranslateUi(DistroMap) self.buttonBox.rejected.connect(DistroMap.reject) QMetaObject.connectSlotsByName(DistroMap) def retranslateUi(self, DistroMap): DistroMap.setWindowTitle(QApplication.translate("DistroMap", "Distribution Map Generator", None)) self.label_5.setText(QApplication.translate("DistroMap", "Point localities layer", None)) self.label_19.setText(QApplication.translate("DistroMap", "Output resolution", None)) self.label_20.setText(QApplication.translate("DistroMap", "x", None)) self.label_21.setText(QApplication.translate("DistroMap", "Map background", None)) self.btnColour.setText(QApplication.translate("DistroMap", "Change", None)) self.label_6.setText(QApplication.translate("DistroMap", "Taxon identifier field", None)) self.label_9.setText(QApplication.translate("DistroMap", "Output directory", None)) self.btnBrowse.setText(QApplication.translate("DistroMap", "Browse...", None)) self.label.setText(QApplication.translate("DistroMap", "Background layers:", None)) self.label_2.setText(QApplication.translate("DistroMap", "Base", None)) self.label_3.setText(QApplication.translate("DistroMap", "Secondary", None)) self.label_4.setText(QApplication.translate("DistroMap", "Surface", None)) self.label_7.setText(QApplication.translate("DistroMap", "Grid layer", None)) self.label_8.setText(QApplication.translate("DistroMap", "Output extent:", None)) self.leMaxY.setText(QApplication.translate("DistroMap", "-21.00", None)) self.leMinX.setText(QApplication.translate("DistroMap", "14.75", None)) self.leMaxX.setText(QApplication.translate("DistroMap", "34.00", None)) self.leMinY.setText(QApplication.translate("DistroMap", "-36.00", None)) self.btnExtent.setText(QApplication.translate("DistroMap", "Use current", None))
class EntityEditorDialog(MapperMixin): """ Dialog for editing entity attributes. """ addedModel = pyqtSignal(object) def __init__(self, entity, model=None, parent=None, manage_documents=True, collect_model=False, parent_entity=None, exclude_columns=None, plugin=None, allow_str_creation=True): """ Class constructor. :param entity: Entity object corresponding to a table object. :type entity: Entity :param model: Data object for loading data into the form widgets. If the model is set, then the editor dialog is assumed to be in edit mode. :type model: object :param parent: Parent widget that the form belongs to. :type parent: QWidget :param manage_documents: True if the dialog should provide controls for managing supporting documents. Only applicable if the entity allows for supporting documents to be attached. :type manage_documents: bool :param collect_model: If set to True only returns the filled form model without saving it to the database. :type collect_model: Boolean :param parent_entity: The parent entity of the editor :type parent_entity: Object :param exclude_columns: List of columns to be excluded if in a list. :type exclude_columns: List :return: If collect_model, returns SQLAlchemy Model """ super().__init__(parent=parent, model=model, entity=entity) QgsGui.enableAutoGeometryRestore(self) self.collection_suffix = self.tr('Collection') # Set minimum width self.setMinimumWidth(450) self.plugin = plugin # Flag for mandatory columns self.has_mandatory = False self.reload_form = False self._entity = entity self.edit_model = model self.column_widgets = OrderedDict() self.columns = {} self._parent = parent self.exclude_columns = exclude_columns or [] self.entity_tab_widget = None self._disable_collections = False self.filter_val = None self.parent_entity = parent_entity self.child_models = OrderedDict() self.entity_scroll_area = None self.entity_editor_widgets = OrderedDict() self.details_tree_view = None # Set notification layout bar self.vlNotification = QVBoxLayout() self.vlNotification.setObjectName('vlNotification') self._notifBar = NotificationBar(self.vlNotification) self.do_not_check_dirty = False # Set manage documents only if the entity supports documents if self._entity.supports_documents: self._manage_documents = manage_documents else: self._manage_documents = False # Setup entity model self._ent_document_model = None if self._entity.supports_documents: self.ent_model, self._ent_document_model = entity_model( self._entity, with_supporting_document=True) else: self.ent_model = entity_model(self._entity) if model is not None: self.ent_model = model MapperMixin.__init__(self, self.ent_model, entity) self.collect_model = collect_model self.register_column_widgets() try: if isinstance(parent._parent, EntityEditorDialog): # hide collections form child editor self._disable_collections = True except AttributeError: self._parent._parent = None # Set title editor_trans = self.tr('Editor') if self._entity.label is not None: if self._entity.label != '': title_str = self._entity.label else: title_str = format_name(self._entity.short_name) else: title_str = format_name(self._entity.short_name) self.title = '{0} {1}'.format(title_str, editor_trans) self.setWindowTitle(self.title) # determine whether the entity is part of the STR relationship curr_profile = current_profile() self.participates_in_str, self.is_party_unit = curr_profile.social_tenure.entity_participates_in_str( self.entity) self._init_gui(show_str_tab=allow_str_creation and self.participates_in_str, is_party_unit=self.is_party_unit) self.adjustSize() self._get_entity_editor_widgets() if isinstance(parent._parent, EntityEditorDialog): self.parent_entity = parent.parent_entity self.set_parent_values() # make the size smaller to differentiate from parent and as it # only has few tabs. self.adjustSize() self.attribute_mappers = self._attr_mapper_collection # Exception title for editor extension exceptions self._ext_exc_msg = self.tr( 'An error has occured while executing Python code in the editor ' 'extension:') # Register custom editor extension if specified self._editor_ext = entity_dlg_extension(self) if self._editor_ext is not None: self._editor_ext.post_init() # Initialize CascadingFieldContext objects self._editor_ext.connect_cf_contexts() def _init_gui(self, show_str_tab: bool, is_party_unit: bool): # Setup base elements self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName('glMain') self.gridLayout.addLayout(self.vlNotification, 0, 0, 1, 1) # set widgets values column_widget_area = self._setup_columns_content_area() self.gridLayout.addWidget(column_widget_area, 1, 0, 1, 1) if show_str_tab: self._setup_str_tab(is_party_unit=is_party_unit) # Add notification for mandatory columns if applicable next_row = 2 if self.has_mandatory: self.required_fields_lbl = QLabel(self) msg = self.tr('Please fill out all required (*) fields.') msg = self._highlight_asterisk(msg) self.required_fields_lbl.setText(msg) self.gridLayout.addWidget(self.required_fields_lbl, next_row, 0, 1, 2) # Bump up row reference next_row += 1 self.buttonBox = QDialogButtonBox(self) self.buttonBox.setObjectName('buttonBox') self.gridLayout.addWidget(self.buttonBox, next_row, 0, 1, 1) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Save) if self.edit_model is None: if not self.collect_model: self.save_new_button = QPushButton( QApplication.translate('EntityEditorDialog', 'Save and New')) self.buttonBox.addButton(self.save_new_button, QDialogButtonBox.ActionRole) # edit model, collect model # adding new record for child # Saving in parent editor if not isinstance(self._parent._parent, EntityEditorDialog): # adding a new record if self.edit_model is None: # saving when digitizing. if self.collect_model: self.buttonBox.accepted.connect(self.on_model_added) # saving parent editor else: self.buttonBox.accepted.connect(self.save_parent_editor) self.save_new_button.clicked.connect(self.save_and_new) # updating existing record else: if not self.collect_model: # updating existing record of the parent editor self.buttonBox.accepted.connect(self.save_parent_editor) else: self.buttonBox.accepted.connect(self.on_model_added) # Saving in child editor else: # save and new record if self.edit_model is None: self.buttonBox.accepted.connect(self.on_child_saved) self.save_new_button.clicked.connect( lambda: self.on_child_saved(True)) else: # When updating an existing child editor save to the db self.buttonBox.accepted.connect(self.on_child_saved) # self.buttonBox.accepted.connect(self.submit) self.buttonBox.rejected.connect(self.cancel) @property def notification_bar(self): """ :return: Returns the dialog's notification bar. :rtype: NotificationBar """ return self._notifBar def save_parent_editor(self): """ Saves the parent editor and its children. """ self.submit() self.save_children() def set_parent_values(self): """ Sets the parent display column for the child. """ if self.parent_entity is None: return for col in self._entity.columns.values(): if col.TYPE_INFO == 'FOREIGN_KEY': parent_entity = col.parent if parent_entity == self.parent_entity: self.parent_widgets_value_setter(self._parent._parent, col) def parent_widgets_value_setter(self, parent, col): """ Finds and sets the value from parent widget and set it to the column widget of a child using the child column. :param parent: The parent widget :type parent: QWidget :param col: The child column object :type col: Object """ for parent_col_name, parent_widget in parent.column_widgets.items(): parent_col = parent.columns[parent_col_name] if parent_col.name == col.name: self.single_parent_value_setter(col, parent_widget) break if parent_col.name in col.entity_relation.display_cols: self.single_parent_value_setter(col, parent_widget) break def single_parent_value_setter(self, col, parent_widget): """ Gets value from parent widget and set it to the column widget of a child using the child column. :param parent: The parent widget :type parent: QWidget :param col: The child column object :type col: Object """ local_widget = self.column_widgets[col.name] local_widget.show_clear_button() self.filter_val = parent_widget.text() local_widget.setText(self.filter_val) def save_and_new(self): """ A slot raised when Save and New button is click. It saves the form without showing a success message. Then it sets reload_form property to True so that entity_browser can re-load the form. """ from stdm.ui.entity_browser import (EntityBrowserWithEditor) self.submit(False, True) self.save_children() if self.is_valid: self.addedModel.emit(self.model()) self.setModel(self.ent_model()) self.clear() self.child_models.clear() for index in range(0, self.entity_tab_widget.count() - 1): if isinstance(self.entity_tab_widget.widget(index), EntityBrowserWithEditor): child_browser = self.entity_tab_widget.widget(index) child_browser.remove_rows() def on_model_added(self): """ A slot raised when a form is submitted with collect model set to True. There will be no success message and the form does not close. """ self.submit(True) self.addedModel.emit(self.model()) def closeEvent(self, event): """ Raised when a request to close the window is received. Check the dirty state of input controls and prompt user to save if dirty. """ if self.do_not_check_dirty: event.accept() return isDirty, userResponse = self.checkDirty() if isDirty: if userResponse == QMessageBox.Yes: # We need to ignore the event so that validation and # saving operations can be executed event.ignore() self.submit() elif userResponse == QMessageBox.No: event.accept() elif userResponse == QMessageBox.Cancel: event.ignore() else: event.accept() def on_child_saved(self, save_and_new=False): """ A slot raised when the save or save and new button is clicked. It sets the child_models dictionary of the parent when saved. :param save_and_new: A boolean indicating the save and new button is clicked to trigger the slot. :type save_and_new: Boolean """ if self.parent_entity is None: return self.submit(True) insert_pos = self._parent.tbEntity.model().rowCount() + 1 # Save to parent editor so that it is persistent. self._parent._parent.child_models[insert_pos, self._entity.name] = \ (self._entity, self.model()) self.addedModel.emit(self.model()) if not save_and_new: self.accept() else: if self.is_valid: # self.addedModel.emit(self.model()) self.setModel(self.ent_model()) self.clear() self.set_parent_values() def save_children(self): """ Saves children models into the database by assigning the the id of the parent for foreign key column. """ if len(self.child_models) < 1: return children_obj = [] for row_entity, row_value in self.child_models.items(): entity, model = row_value ent_model = entity_model(entity) entity_obj = ent_model() for col in entity.columns.values(): if col.TYPE_INFO == 'FOREIGN_KEY': if col.parent.name == self._entity.name: setattr(model, col.name, self.model().id) children_obj.append(model) entity_obj.saveMany(children_obj) def register_column_widgets(self): """ Registers the column widgets. """ # Append column labels and widgets table_name = self._entity.name columns = table_column_names(table_name) self.scroll_widget_contents = QWidget() self.scroll_widget_contents.setObjectName('scrollAreaWidgetContents') for c in self._entity.columns.values(): if c.name in self.exclude_columns: continue if c.name not in columns and not isinstance(c, VirtualColumn): continue # Get widget factory column_widget = ColumnWidgetRegistry.create( c, self.scroll_widget_contents, host=self) self.columns[c.name] = c self.column_widgets[c.name] = column_widget def _setup_columns_content_area(self): # Only use this if entity supports documents # self.entity_tab_widget = None self.doc_widget = None self.entity_scroll_area = QScrollArea(self) self.entity_scroll_area.setFrameShape(QFrame.NoFrame) self.entity_scroll_area.setWidgetResizable(True) self.entity_scroll_area.setObjectName('scrollArea') # Grid layout for controls self.gl = QGridLayout(self.scroll_widget_contents) self.gl.setObjectName('gl_widget_contents') # Append column labels and widgets table_name = self._entity.name columns = table_column_names(table_name) # Iterate entity column and assert if they exist row_id = 0 for column_name, column_widget in self.column_widgets.items(): c = self.columns[column_name] if c.name in self.exclude_columns: continue if c.name not in columns and not isinstance(c, VirtualColumn): continue if column_widget is not None: header = c.ui_display() self.c_label = QLabel(self.scroll_widget_contents) # Format label text if it is a mandatory field if c.mandatory: header = '{0} *'.format(c.ui_display()) # Highlight asterisk header = self._highlight_asterisk(header) self.c_label.setText(header) self.gl.addWidget(self.c_label, row_id, 0, 1, 1) self.column_widget = column_widget self.gl.addWidget(self.column_widget, row_id, 1, 1, 1) # Add user tip if specified for the column configuration if c.user_tip: self.tip_lbl = UserTipLabel(user_tip=c.user_tip) self.gl.addWidget(self.tip_lbl, row_id, 2, 1, 1) if c.mandatory and not self.has_mandatory: self.has_mandatory = True col_name = c.name # Replace name accordingly based on column type if isinstance(c, MultipleSelectColumn): col_name = c.model_attribute_name # Add widget to MapperMixin collection self.addMapping(col_name, self.column_widget, c.mandatory, pseudoname=c.ui_display()) # Bump up row_id row_id += 1 self.entity_scroll_area.setWidget(self.scroll_widget_contents) if self.entity_tab_widget is None: self.entity_tab_widget = QTabWidget(self) # Check if there are children and add foreign key browsers # Add primary tab if necessary self._add_primary_attr_widget() if not self._disable_collections: ch_entities = self.children_entities() for col, ch in ch_entities: if hasattr(col.entity_relation, 'show_in_parent'): if col.entity_relation.show_in_parent != '0': self._add_fk_browser(ch, col) else: self._add_fk_browser(ch, col) # Add tab widget if entity supports documents if self._entity.supports_documents: self.doc_widget = SupportingDocumentsWidget( self._entity.supporting_doc, self._ent_document_model, self) # Map the source document manager object self.addMapping('documents', self.doc_widget.source_document_manager) # # # Add attribute tab # self._add_primary_attr_widget() # Add supporting documents tab self.entity_tab_widget.addTab(self.doc_widget, self.tr('Supporting Documents')) # Return the correct widget if self.entity_tab_widget is not None: return self.entity_tab_widget return self.entity_scroll_area def _add_primary_attr_widget(self): # Check if the primary entity # exists and add if it does not pr_txt = self.tr('Primary') if self.entity_tab_widget is not None: tab_txt = self.entity_tab_widget.tabText(0) if not tab_txt == pr_txt: self.entity_tab_widget.addTab(self.entity_scroll_area, pr_txt) def _setup_str_tab(self, is_party_unit: bool): """ Creates the STR relationship tab """ from stdm.ui.feature_details import DetailsTreeView layout = QVBoxLayout() hl = QHBoxLayout() add_btn = QToolButton(self) add_btn.setText(self.tr('Create STR')) add_btn.setIcon(GuiUtils.get_icon('add.png')) hl.addWidget(add_btn) add_btn.clicked.connect(self._create_str) edit_btn = QToolButton(self) edit_btn.setText(self.tr('Edit')) edit_btn.setIcon(GuiUtils.get_icon('edit.png')) edit_btn.setDisabled(True) hl.addWidget(edit_btn) view_document_btn = QToolButton(self) view_document_btn.setText(self.tr('View Supporting Documents')) view_document_btn.setIcon(GuiUtils.get_icon('document.png')) view_document_btn.setDisabled(True) hl.addWidget(view_document_btn) hl.addStretch() layout.addLayout(hl) self.details_tree_view = DetailsTreeView( parent=self, plugin=self.plugin, edit_button=edit_btn, view_document_button=view_document_btn) self.details_tree_view.activate_feature_details( True, follow_layer_selection=False) self.details_tree_view.model.clear() if is_party_unit: self.details_tree_view.search_party(self.entity, [self.ent_model.id]) else: self.details_tree_view.search_spatial_unit(self.entity, [self.ent_model.id]) layout.addWidget(self.details_tree_view) w = QWidget() w.setLayout(layout) self.entity_tab_widget.addTab(w, self.tr('STR')) def _create_str(self): """ Opens the dialog to create a new STR """ from stdm.ui.social_tenure.str_editor import STREditor add_str_window = STREditor() #if is_party_unit: # add_str.set_party_data(self.entity_model_obj) if add_str_window.exec_(): # STR created - refresh STR view if self.is_party_unit: self.details_tree_view.search_party(self.entity, [self.ent_model.id]) else: self.details_tree_view.search_spatial_unit( self.entity, [self.ent_model.id]) def _add_fk_browser(self, child_entity, column): # Create and add foreign key # browser to the collection from stdm.ui.entity_browser import (ContentGroupEntityBrowser) attr = '{0}_collection'.format(child_entity.name) # Return if the attribute does not exist if not hasattr(self._model, attr): return table_content = TableContentGroup(User.CURRENT_USER.UserName, child_entity.short_name) if self.edit_model is not None: parent_id = self.edit_model.id else: parent_id = 0 entity_browser = ContentGroupEntityBrowser(child_entity, table_content, rec_id=parent_id, parent=self, plugin=self.plugin, load_recs=False) # entity_browser = EntityBrowserWithEditor( # child_entity, # self, # MANAGE, # False, # plugin=self.plugin # ) entity_browser.buttonBox.setVisible(False) entity_browser.record_filter = [] if len(child_entity.label) > 2: column_label = child_entity.label else: # Split and join to filter out entity name prefix # e.g. 'lo_parcel' to 'parcel' column_label = format_name(" ".join( child_entity.name.split("_", 1)[1:])) self.set_filter(child_entity, entity_browser) self.entity_tab_widget.addTab(entity_browser, '{0}'.format(column_label)) def set_filter(self, entity, browser): col = self.filter_col(entity) child_model = entity_model(entity) child_model_obj = child_model() col_obj = getattr(child_model, col.name) browser.filtered_records = [] if self.model() is not None: if self.model().id is not None: browser.filtered_records = child_model_obj.queryObject( ).filter(col_obj == self.model().id).all() if self.edit_model is not None: browser.filtered_records = child_model_obj.queryObject().filter( col_obj == self.edit_model.id).all() def filter_col(self, child_entity): for col in child_entity.columns.values(): if col.TYPE_INFO == 'FOREIGN_KEY': parent_entity = col.parent if parent_entity == self._entity: return col def children_entities(self): """ :return: Returns a list of children entities (by name) that refer to the main entity as the parent. :rtype: OrderedDict """ child_columns = [] for ch in self._entity.children(): if ch.TYPE_INFO == Entity.TYPE_INFO: for col in ch.columns.values(): if hasattr(col, 'entity_relation'): if col.parent.name == self._entity.name: child_columns.append((col, ch)) return child_columns def document_widget(self): """ :return: Returns the widget for managing the supporting documents for an entity if enabled. :rtype: SupportingDocumentsWidget """ return self.doc_widget def source_document_manager(self): """ :return: Returns an instance of the SourceDocumentManager only if supporting documents are enabled for the given entity. Otherwise, None if supporting documents are not enabled. :rtype: SourceDocumentManager """ if self.doc_widget is None: return None return self.doc_widget.source_document_manager def _highlight_asterisk(self, text): # Highlight asterisk in red c = '*' # Do not format if there is no asterisk if text.find(c) == -1: return text asterisk_highlight = '<span style=\" color:#ff0000;\">*</span>' text = text.replace(c, asterisk_highlight) return '<html><head/><body><p>{0}</p></body></html>'.format(text) def _custom_validate(self): """ Override of the MapperMixin which enables custom editor extensions to inject additional validation before saving form data. :return: Return True if the validation was successful, otherwise False. :rtype: bool """ if self._editor_ext is not None: return self._editor_ext.validate() # Return True if there is no custom editor extension specified return True def _post_save(self, model): """ Include additional post-save logic by custom extensions. :param model: SQLAlchemy model :type model: object """ if self._editor_ext is not None: self._editor_ext.post_save(model) def _get_entity_editor_widgets(self): """ Gets entity editor widgets and appends them to a dictionary """ if self.entity_tab_widget: tab_count = self.entity_tab_widget.count() for i in range(tab_count): tab_object = self.entity_tab_widget.widget(i) tab_text = self.entity_tab_widget.tabText(i) self.entity_editor_widgets[tab_text] = tab_object else: self.entity_editor_widgets['no_tab'] = self.entity_scroll_area
class AdvancedSearch(EntityEditorDialog): def __init__(self, entity, parent): EntityEditorDialog.__init__(self, entity, parent=parent) self.parent = parent def _init_gui(self): # Setup base elements self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName('glMain') self.gridLayout.addLayout(self.vlNotification, 0, 0, 1, 1) QApplication.processEvents() column_widget_area = self._setup_columns_content_area() self.gridLayout.addWidget(column_widget_area, 1, 0, 1, 1) QApplication.processEvents() # Add notification for mandatory columns if applicable next_row = 2 # Set title search_trans = self.tr('Advanced Search') if self._entity.label is not None: if self._entity.label != '': title_str = self._entity.label else: title_str = format_name(self._entity.short_name) else: title_str = format_name(self._entity.short_name) title = '{0} {1}'.format(title_str, search_trans) self.do_not_check_dirty = True self.setWindowTitle(title) # if self.has_mandatory: # self.required_fields_lbl = QLabel(self) # msg = self.tr( # 'Please fill out all required (*) fields.' # ) # msg = self._highlight_asterisk(msg) # self.required_fields_lbl.setText(msg) # self.gridLayout.addWidget( # self.required_fields_lbl, next_row, 0, 1, 2 # ) # # Bump up row reference # next_row += 1 self.buttonBox = QDialogButtonBox(self) self.buttonBox.setObjectName('buttonBox') self.gridLayout.addWidget(self.buttonBox, next_row, 0, 1, 1) self.buttonBox.setOrientation(Qt.Horizontal) self.search = QPushButton( QApplication.translate('EntityEditorDialog', 'Search')) self.buttonBox.addButton(self.search, QDialogButtonBox.ActionRole) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel) self.search.clicked.connect(self.on_search) # # # # edit model, collect model # # adding new record for child # # # Saving in parent editor # if not isinstance(self._parent._parent, EntityEditorDialog): # # adding a new record # if self.edit_model is None: # # saving when digitizing. # if self.collect_model: # self.buttonBox.accepted.connect(self.on_model_added) # # saving parent editor # else: # self.buttonBox.accepted.connect(self.save_parent_editor) # self.save_new_button.clicked.connect(self.save_and_new) # # updating existing record # else: # if not self.collect_model: # # updating existing record of the parent editor # self.buttonBox.accepted.connect(self.save_parent_editor) # else: # self.buttonBox.accepted.connect(self.on_model_added) # # Saving in child editor # else: # # save and new record # if self.edit_model is None: # self.buttonBox.accepted.connect(self.on_child_saved) # self.save_new_button.clicked.connect( # lambda: self.on_child_saved(True) # ) # # else: # # When updating an existing child editor save to the db # self.buttonBox.accepted.connect( # self.on_child_saved # ) # #self.buttonBox.accepted.connect(self.submit) # self.buttonBox.rejected.connect(self.cancel) def on_search(self): search_data = {} for column in self._entity.columns.values(): if column.name in entity_display_columns(self._entity): if column.name == 'id': continue handler = self.attribute_mappers[column.name].valueHandler() value = handler.value() if value != handler.default() and bool(value): search_data[column.name] = value # self.search_db(search_data) result = self.search_db_raw(search_data) self.parent._tableModel.removeRows(0, self.parent._tableModel.rowCount()) if result is not None: found = QApplication.translate('AdvancedSearch', 'records found') new_title = '{} - {} {}'.format(self.title, result.rowcount, found) if result.rowcount > 3000: title = QApplication.translate('AdvancedSearch', 'Advanced Search') message = QApplication.translate( 'AdvancedSearch', 'The search result returned {0} records, which is above the ' 'search result limit. <br>Would you like to see the first 3000 ' 'records?'.format("{:,}".format(result.rowcount))) res, chk_result = simple_dialog(self, title, message) if res: self.setWindowTitle(new_title) self.parent._initializeData(result) else: return else: self.setWindowTitle(new_title) self.parent._initializeData(result) def search_db(self, search_data): ent_model_obj = self.ent_model() # query = ent_model_obj.queryObject() for attr, value in search_data.items(): ent_model_obj.queryObject().filter( getattr(self.ent_model(), attr) == value) # now we can run the query # print(ent_model_obj.queryObject(), vars(ent_model_obj.queryObject())) # print(str(ent_model_obj.queryObject())) results = ent_model_obj.queryObject().all() def search_db_raw(self, search_data): sql = "SELECT * FROM {} WHERE ".format(self._entity.name) # query = ent_model_obj.queryObject() param = [] if len(search_data) == 0: return None for attr, value in search_data.items(): if isinstance(value, (int, float)): param.append('{} = {}'.format(str(attr), str(value))) if isinstance(value, str): param.append("{} = '{}'".format(str(attr), str(value))) final_sql = '{} {}'.format(sql, ' AND '.join(param)) # sql_text = text(final_sql) results = fetch_with_filter(final_sql) # now we can run the query return results def _setup_columns_content_area(self): # Only use this if entity supports documents # self.entity_tab_widget = None self.doc_widget = None self.entity_scroll_area = QScrollArea(self) self.entity_scroll_area.setFrameShape(QFrame.NoFrame) self.entity_scroll_area.setWidgetResizable(True) self.entity_scroll_area.setObjectName('scrollArea') # Grid layout for controls self.gl = QGridLayout(self.scroll_widget_contents) self.gl.setObjectName('gl_widget_contents') # Append column labels and widgets table_name = self._entity.name columns = table_column_names(table_name) # Iterate entity column and assert if they exist row_id = 0 for column_name, column_widget in self.column_widgets.items(): c = self.columns[column_name] if c.name in self.exclude_columns: continue if isinstance(c, MultipleSelectColumn): continue if not c.name in columns and not isinstance(c, VirtualColumn): continue if column_widget is not None: header = c.ui_display() self.c_label = QLabel(self.scroll_widget_contents) self.c_label.setText(header) self.gl.addWidget(self.c_label, row_id, 0, 1, 1) if c.TYPE_INFO == 'AUTO_GENERATED': column_widget.setReadOnly(False) column_widget.btn_load.hide() self.gl.addWidget(column_widget, row_id, 1, 1, 1) col_name = c.name # Add widget to MapperMixin collection self.addMapping(col_name, column_widget, c.mandatory, pseudoname=c.ui_display()) # Bump up row_id row_id += 1 self.entity_scroll_area.setWidget(self.scroll_widget_contents) if self.entity_tab_widget is None: self.entity_tab_widget = QTabWidget(self) # Check if there are children and add foreign key browsers # Add primary tab if necessary self._add_primary_attr_widget() # self.entity_tab_widget.setTabEnabled(0, False) # enable/disable the tab # set the style sheet self.setStyleSheet( "QTabBar::tab::selected {width: 0; height: 0; margin: 0; " "padding: 0; border: none;} ") # Return the correct widget if self.entity_tab_widget is not None: return self.entity_tab_widget return self.entity_scroll_area def closeEvent(self, event): ''' Raised when a request to close the window is received. Check the dirty state of input controls and prompt user to save if dirty. ''' event.accept() def cancel(self): ''' Slot for closing the dialog. Checks the dirty state first before closing. ''' self.reject()
def initialize_widgets(self): """Dynamically set up widgets based on detected files.""" self.widgets_per_file.clear() files_widgets = [ self.widget_general, self.widget_terrain_model, self.widget_simple_infiltration, self.widget_groundwater, self.widget_interflow, ] files_info_collection = [ self.general_files, self.terrain_model_files, self.simple_infiltration_files, self.groundwater_files, self.interflow_files, ] for widget in files_widgets: widget.hide() current_main_layout_row = 1 for widget, files_info in zip(files_widgets, files_info_collection): widget_layout = widget.layout() for field_name, name in files_info.items(): try: file_state = self.detected_files[field_name] except KeyError: continue status = file_state["status"] widget.show() name_label = QLabel(name) name_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) widget_layout.addWidget(name_label, current_main_layout_row, 0) status_label = QLabel(status.value) status_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) widget_layout.addWidget(status_label, current_main_layout_row, 1) empty_label = QLabel() widget_layout.addWidget(empty_label, current_main_layout_row, 2) no_action_pb_name = "Ignore" if status == UploadFileStatus.DELETED_LOCALLY: action_pb_name = "Delete online" else: action_pb_name = "Upload" # Add valid reference widgets all_actions_widget = QWidget() actions_sublayout = QGridLayout() all_actions_widget.setLayout(actions_sublayout) valid_ref_widget = QWidget() valid_ref_sublayout = QGridLayout() valid_ref_widget.setLayout(valid_ref_sublayout) no_action_pb = QPushButton(no_action_pb_name) no_action_pb.setCheckable(True) no_action_pb.setAutoExclusive(True) no_action_pb.clicked.connect( partial(self.toggle_action, field_name, False)) action_pb = QPushButton(action_pb_name) action_pb.setCheckable(True) action_pb.setAutoExclusive(True) action_pb.setChecked(True) action_pb.clicked.connect( partial(self.toggle_action, field_name, True)) valid_ref_sublayout.addWidget(no_action_pb, 0, 0) valid_ref_sublayout.addWidget(action_pb, 0, 1) # Add invalid reference widgets invalid_ref_widget = QWidget() invalid_ref_sublayout = QGridLayout() invalid_ref_widget.setLayout(invalid_ref_sublayout) filepath_sublayout = QGridLayout() filepath_line_edit = QLineEdit() filepath_line_edit.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) browse_pb = QPushButton("...") browse_pb.clicked.connect( partial(self.browse_for_raster, field_name)) filepath_sublayout.addWidget(filepath_line_edit, 0, 0) filepath_sublayout.addWidget(browse_pb, 0, 1) invalid_ref_sublayout.addLayout(filepath_sublayout, 0, 0) update_ref_pb = QPushButton("Update reference") update_ref_pb.clicked.connect( partial(self.update_raster_reference, field_name)) invalid_ref_sublayout.addWidget(update_ref_pb, 0, 1) actions_sublayout.addWidget(valid_ref_widget, 0, 0) actions_sublayout.addWidget(invalid_ref_widget, 0, 1) # Add all actions widget into the main widget layout widget_layout.addWidget(all_actions_widget, current_main_layout_row, 2) # Hide some of the widgets based on files states if status == UploadFileStatus.NO_CHANGES_DETECTED: all_actions_widget.hide() elif status == UploadFileStatus.INVALID_REFERENCE: valid_ref_widget.hide() else: invalid_ref_widget.hide() self.widgets_per_file[field_name] = ( name_label, status_label, valid_ref_widget, action_pb, invalid_ref_widget, filepath_line_edit, ) current_main_layout_row += 1