class ServiceConfigurationDialog(QDialog): """ A dialog for configuring a service """ def __init__(self, iface, service_type: str, service_id: str, parent: Optional[QWidget]): super().__init__(parent) self.setObjectName('ServiceConfigurationDialog') QgsGui.enableAutoGeometryRestore(self) self.setWindowTitle(self.tr('Edit Service {}').format(service_id)) self.config_widget = ServiceConfigurationWidget( iface, service_type, service_id) layout = QVBoxLayout() layout.addWidget(self.config_widget, 1) self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) layout.addWidget(self.button_box) self.setLayout(layout) self.config_widget.validChanged.connect(self.valid_changed) self.valid_changed(self.config_widget.is_valid()[0]) def valid_changed(self, is_valid: bool): """ Triggered when the widget valid state is changed """ self.button_box.button(QDialogButtonBox.Ok).setEnabled(is_valid) def accept(self): # pylint: disable=missing-function-docstring self.config_widget.save_changes() super().accept()
class CommitDialog(QDialog): def __init__(self, repo, layername, _message="", parent=None): super(CommitDialog, self).__init__(parent) self.repo = repo self.branch = None self.layername = layername self._message = _message or suggestedMessage self.message = None self.initGui() def initGui(self): self.setObjectName("CommitDialog") self.resize(600, 250) self.setWindowTitle("Syncronize layer to repository branch") self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(5) self.branchLabel = QLabel("Branch") self.verticalLayout.addWidget(self.branchLabel) self.branchCombo = QComboBox() self.branches = [] branches = self.repo.branches() for branch in branches: trees = self.repo.trees(branch) if self.layername in trees: self.branches.append(branch) self.branchCombo.addItems(self.branches) try: idx = self.branches.index("master") except: idx = 0 self.branchCombo.setCurrentIndex(idx) self.verticalLayout.addWidget(self.branchCombo) self.msgLabel = QLabel("Message to describe this update") self.verticalLayout.addWidget(self.msgLabel) self.text = QPlainTextEdit() self.text.setPlainText(self._message) self.verticalLayout.addWidget(self.text) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) self.verticalLayout.addWidget(self.buttonBox) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( bool(self.branches)) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.text.setFocus() def okPressed(self): self.branch = self.branchCombo.currentText() self.message = self.text.toPlainText() or datetime.now().strftime( "%Y-%m-%d %H_%M_%S") self.close()
class ServiceConfigurationDialog(QDialog): def __init__(self, iface, service_type, service_id, parent): super().__init__(parent) self.setObjectName('ServiceConfigurationDialog') QgsGui.enableAutoGeometryRestore(self) self.setWindowTitle(self.tr('Edit Service {}').format(service_id)) self.config_widget = ServiceConfigurationWidget( iface, service_type, service_id) layout = QVBoxLayout() layout.addWidget(self.config_widget, 1) self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) layout.addWidget(self.button_box) self.setLayout(layout) self.config_widget.validChanged.connect(self.valid_changed) self.valid_changed(self.config_widget.is_valid()[0]) def valid_changed(self, is_valid): self.button_box.button(QDialogButtonBox.Ok).setEnabled(is_valid) def accept(self): self.config_widget.save_changes() super().accept()
def runImportObservationData(self): # Get the list of series series = self.getSeries() if not series: return # Create dialog to let the user choose the serie dialog = QDialog() dialog.setWindowTitle(tr('Import observation data')) layout = QVBoxLayout() dialog.setLayout(layout) # Combobox combo_box = QComboBox() combo_box.setObjectName((tr('Choose series'))) for i, d in enumerate(series): combo_box.addItem(d[1]) combo_box.setItemData(i, d[0]) layout.addWidget(combo_box) # Validation button button_box = QDialogButtonBox() button_box.addButton(QDialogButtonBox.Ok) button_box.button(QDialogButtonBox.Ok).clicked.connect(dialog.accept) layout.addWidget(button_box) if dialog.exec_() == QDialog.Accepted: idx = combo_box.currentIndex() val = combo_box.itemData(idx) self.openImportObservationData(val)
class TagNameDialog(QDialog): def __init__(self, dockwidget, parent): QDialog.__init__(self, parent) main_lay = QVBoxLayout(self) self.dockwidget = dockwidget self.tag_name = None self.setWindowTitle('Tag name') # Top frame self.fra_top = QFrame() fra_top_lay = QVBoxLayout(self.fra_top) self.lbl_explanation = QLabel('Insert a name (no blanks allowed)') fra_top_lay.addWidget(self.lbl_explanation) self.txt_name = QLineEdit() self.txt_name.setValidator(RegExValidators.get_no_blanks()) fra_top_lay.addWidget(self.txt_name) # Button box self.btb_main = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.btb_main.accepted.connect(self.ok) self.btb_main.rejected.connect(self.reject) # Bottom frame self.fra_bottom = QFrame() fra_bottom_lay = QHBoxLayout(self.fra_bottom) fra_bottom_lay.addWidget(self.btb_main) # Main main_lay.addWidget(self.fra_top) main_lay.addWidget(self.fra_bottom) self.initialize() def initialize(self): self.btb_main.button(QDialogButtonBox.Ok).setEnabled(False) self.txt_name.textChanged.connect(self.text_changed) def ok(self): self.tag_name = self.txt_name.text() self.setVisible(False) def reject(self): self.tag_name = None self.setVisible(False) def text_changed(self): self.btb_main.button(QDialogButtonBox.Ok).setEnabled(self.txt_name != '') def get_tag_name(self): return self.tag_name
def setupUi(self): ''' set up the user interface ''' self.setMinimumWidth(500) self.setWindowTitle('Neues Projekt erstellen') project_manager = ProjectManager() self.project_names = [p.name for p in project_manager.projects] layout = QVBoxLayout(self) label = QLabel('Name des Projekts') self.name_edit = QLineEdit() self.name_edit.textChanged.connect(self.validate) layout.addWidget(label) layout.addWidget(self.name_edit) self.path = os.path.join(project_manager.settings.TEMPLATE_PATH, 'projektflaechen') hlayout = QHBoxLayout(self) label = QLabel('Import der (Teil-)Flächen des Plangebiets') self.layer_combo = QgsMapLayerComboBox() self.layer_combo.setFilters(QgsMapLayerProxyModel.VectorLayer) self.source = None self.layer_combo.layerChanged.connect(self.set_layer) self.layer_combo.layerChanged.connect(self.validate) browse_button = QPushButton('...') browse_button.clicked.connect(self.browse_path) browse_button.setMaximumWidth(30) hlayout.addWidget(self.layer_combo) hlayout.addWidget(browse_button) layout.addWidget(label) layout.addLayout(hlayout) self.status_label = QLabel() layout.addWidget(self.status_label) spacer = QSpacerItem( 20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) layout.addItem(spacer) buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.ok_button = buttons.button(QDialogButtonBox.Ok) self.ok_button.setEnabled(False) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) layout.addWidget(buttons) if len(self.layer_combo) > 0: self.set_layer(self.layer_combo.currentLayer()) self.layer_combo.setCurrentIndex(0)
def __init__(self, parent): """Small window to define the name of the saved parmeter set.""" QDialog.__init__(self, parent) self.paramData = None self.availableSets = None self.savePath = None self.setname = None self.setWindowTitle(self.tr('Name Parameterset')) main_widget = QWidget(self) # Build gui hbox = QHBoxLayout() setnameLabel = QLabel(self.tr('Bezeichnung Parameterset')) self.setnameField = QLineEdit() self.setnameField.setMinimumWidth(400) self.setnameField.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)) hbox.addWidget(setnameLabel) hbox.addWidget(self.setnameField) # Create Ok/Cancel Button and connect signal buttonBox = QDialogButtonBox(main_widget) buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) buttonBox.button(QDialogButtonBox.Ok).setText(self.tr("OK")) buttonBox.button(QDialogButtonBox.Cancel).setText(self.tr("Abbrechen")) buttonBox.accepted.connect(self.apply) buttonBox.rejected.connect(self.onCancel) # Layout container = QVBoxLayout(main_widget) container.addLayout(hbox) container.addWidget(buttonBox) container.setAlignment(Qt.AlignLeft) self.setLayout(container)
class ParamBox(QDialog): """ Param box of the plugin """ def __init__(self, parent=None, tree_dock=None): QWidget.__init__(self, parent) self.tree_dock = tree_dock # Init GUI self.init_gui() # Evaluate flags and tupdate the state of the Apply button self.evaluate_flags() def init_gui(self): """ """ dlg_layout = QVBoxLayout() params_layout = QVBoxLayout() params_layout.setAlignment(Qt.AlignTop) # Config files groupbox self.config_files_groupbox = QgsCollapsibleGroupBox( u"Fichier de configuration de l'arbre des ressources") config_file_groupbox_layout = QFormLayout(self.config_files_groupbox) # URL of the file self.config_file_url_label = QLabel(u"URL du fichier", self) self.config_file_url_edit = QLineEdit(self) self.config_file_url_edit.editingFinished.connect( self.config_file_url_changed) config_file_groupbox_layout.addRow(self.config_file_url_label, self.config_file_url_edit) # Download the file at startup self.download_cb = QCheckBox( u"Télécharger le fichier à chaque lancement de QGIS", self) self.download_cb.stateChanged.connect(self.download_cb_changed) config_file_groupbox_layout.addRow(self.download_cb) params_layout.addWidget(self.config_files_groupbox) # Download the file now self.download_now_label = QLabel(u"Télécharger le fichier maintenant", self) self.download_now_btnbox = QDialogButtonBox() self.download_now_btnbox.setOrientation(Qt.Horizontal) self.download_now_btnbox.setStandardButtons(QDialogButtonBox.Yes) self.download_now_btnbox.button(QDialogButtonBox.Yes).clicked.connect( self.download_file_now) config_file_groupbox_layout.addRow(self.download_now_label, self.download_now_btnbox) # Content of the resource tree groupbox self.resource_tree_groupbox = QgsCollapsibleGroupBox( u"Contenu de l'arbre des ressources") resource_tree_groupbox_layout = QFormLayout( self.resource_tree_groupbox) # Hide resources with a warn flag self.hide_resources_with_warn_status_cb = QCheckBox( u"Masquer les ressources en cours d'intégration", self) self.hide_resources_with_warn_status_cb.stateChanged.connect( self.hide_resources_with_warn_cb_changed) resource_tree_groupbox_layout.addRow( self.hide_resources_with_warn_status_cb) # Hide empty groups in the resources tree self.hide_empty_groups_cb = QCheckBox( u"Masquer les groupes de ressources vides", self) self.hide_empty_groups_cb.stateChanged.connect( self.hide_empty_groups_cb_changed) resource_tree_groupbox_layout.addRow(self.hide_empty_groups_cb) params_layout.addWidget(self.resource_tree_groupbox) dlg_layout.addLayout(params_layout) # Set values self.set_values_from_qsettings() # Bottom dialog buttons self.button_box = QDialogButtonBox() self.button_box.setOrientation(Qt.Horizontal) self.button_box.setStandardButtons(QDialogButtonBox.RestoreDefaults | QDialogButtonBox.Apply | QDialogButtonBox.Close) self.button_box.button( QDialogButtonBox.RestoreDefaults).clicked.connect( self.restore_defaults_button_clicked) self.button_box.button(QDialogButtonBox.Close).clicked.connect( self.close_button_clicked) self.button_box.button(QDialogButtonBox.Apply).clicked.connect( self.apply_button_clicked) # Dialog box title, layout, size and display title = u"Paramétrage de l'extension GéoSAS…" self.setWindowTitle(title) dlg_layout.addWidget(self.button_box) self.setLayout(dlg_layout) self.setMinimumWidth(500) self.resize(self.sizeHint()) self.setSizeGripEnabled(False) self.setFixedSize(self.size()) self.show() self.setSizeGripEnabled(False) def set_values_from_qsettings(self): """ """ # URL of the file self.config_file_url_edit.blockSignals(True) self.config_file_url_edit.setText( PluginGlobals.instance().CONFIG_FILE_URLS[0]) self.config_file_url_edit.setCursorPosition(0) self.config_file_url_edit.blockSignals(False) # Download the file at startup self.download_cb.blockSignals(True) self.download_cb.setChecked( PluginGlobals.instance().CONFIG_FILES_DOWNLOAD_AT_STARTUP) self.download_cb.blockSignals(True) # Hide resources with a warn flag self.hide_resources_with_warn_status_cb.blockSignals(True) self.hide_resources_with_warn_status_cb.setChecked( PluginGlobals.instance().HIDE_RESOURCES_WITH_WARN_STATUS) self.hide_resources_with_warn_status_cb.blockSignals(False) # Hide empty groups in the resources tree self.hide_empty_groups_cb.blockSignals(True) self.hide_empty_groups_cb.setChecked( PluginGlobals.instance().HIDE_EMPTY_GROUPS) self.hide_empty_groups_cb.blockSignals(False) def evaluate_flags(self): """ """ # Detect modifications file_url_changed = (self.config_file_url_edit.text() != PluginGlobals.instance().CONFIG_FILE_URLS[0]) download_at_startup_changed = \ (self.download_cb.isChecked() != PluginGlobals.instance().CONFIG_FILES_DOWNLOAD_AT_STARTUP) hide_resources_with_warn_status_changed = \ (self.hide_resources_with_warn_status_cb.isChecked() != PluginGlobals.instance().HIDE_RESOURCES_WITH_WARN_STATUS) hide_empty_groups_changed = \ (self.hide_empty_groups_cb.isChecked() != PluginGlobals.instance().HIDE_EMPTY_GROUPS) # Init flags self.need_update_visibility_of_tree_items = hide_empty_groups_changed or hide_resources_with_warn_status_changed self.need_update_of_tree_content = file_url_changed self.need_save = file_url_changed or download_at_startup_changed or \ hide_resources_with_warn_status_changed or \ hide_empty_groups_changed # Update state of the Apply Button self.button_box.button(QDialogButtonBox.Apply).setEnabled( self.need_save) def download_cb_changed(self, state): """ Event sent when the state of the checkbox change """ self.evaluate_flags() def config_file_url_changed(self): """ Event sent when the text of the line edit has been edited """ self.evaluate_flags() def hide_resources_with_warn_cb_changed(self, state): """ Event sent when the state of the checkbox change """ self.evaluate_flags() def hide_empty_groups_cb_changed(self, state): """ Event sent when the state of the checkbox change """ self.evaluate_flags() def download_file_now(self): """ """ # Download, read the resources tree file and update the GUI download_tree_config_file(self.config_file_url_edit.text()) self.ressources_tree = TreeNodeFactory( PluginGlobals.instance().config_file_path).root_node if self.tree_dock is not None: self.tree_dock.set_tree_content(self.ressources_tree) def save_settings(self): """ """ # URL of the file new_value = [self.config_file_url_edit.text()] PluginGlobals.instance().set_qgis_settings_value( "config_file_urls", new_value) # Download the file at startup new_value = self.download_cb.isChecked() PluginGlobals.instance().set_qgis_settings_value( "config_files_download_at_startup", new_value) # Hide resources with a warn flag new_value = self.hide_resources_with_warn_status_cb.isChecked() PluginGlobals.instance().set_qgis_settings_value( "hide_resources_with_warn_status", new_value) # Hide empty groups in the resources tree new_value = self.hide_empty_groups_cb.isChecked() PluginGlobals.instance().set_qgis_settings_value( "hide_empty_groups", new_value) # Download, read the resources tree file and update the GUI if self.need_update_of_tree_content: download_tree_config_file( PluginGlobals.instance().CONFIG_FILE_URLS[0]) self.ressources_tree = TreeNodeFactory( PluginGlobals.instance().config_file_path).root_node self.tree_dock.set_tree_content(self.ressources_tree) # Update the visibility of tree items elif self.need_update_visibility_of_tree_items and self.tree_dock is not None: self.tree_dock.update_visibility_of_tree_items() def apply_button_clicked(self): """ """ self.save_settings() self.evaluate_flags() def close_button_clicked(self): """ """ self.close() def restore_defaults_button_clicked(self): """ """ # URL of the file self.config_file_url_edit.blockSignals(True) self.config_file_url_edit.setText( PluginGlobals.instance().get_qgis_setting_default_value( "CONFIG_FILE_URLS")[0]) self.config_file_url_edit.setCursorPosition(0) self.config_file_url_edit.blockSignals(False) # Download the file at startup self.download_cb.blockSignals(True) self.download_cb.setChecked( PluginGlobals.instance().get_qgis_setting_default_value( "CONFIG_FILES_DOWNLOAD_AT_STARTUP")) self.download_cb.blockSignals(False) # Hide resources with a warn flag self.hide_resources_with_warn_status_cb.blockSignals(True) self.hide_resources_with_warn_status_cb.setChecked( PluginGlobals.instance().get_qgis_setting_default_value( "HIDE_RESOURCES_WITH_WARN_STATUS")) self.hide_resources_with_warn_status_cb.blockSignals(False) # Hide empty groups in the resources tree self.hide_empty_groups_cb.blockSignals(True) self.hide_empty_groups_cb.setChecked( PluginGlobals.instance().get_qgis_setting_default_value( "HIDE_EMPTY_GROUPS")) self.hide_empty_groups_cb.blockSignals(False) self.evaluate_flags() def closeEvent(self, evnt): """ """ if self.need_save: reply = QMessageBox.question( self, u"Sauvegarder ?", u"Voulez-vous appliquer les changements avant de fermer la fenêtre de paramétrage de l'extension ?", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Yes) if reply == QMessageBox.No: evnt.accept() super(ParamBox, self).closeEvent(evnt) elif reply == QMessageBox.Yes: self.save_settings() evnt.accept() super(ParamBox, self).closeEvent(evnt) else: evnt.accept() super(ParamBox, self).closeEvent(evnt) evnt.ignore()
class CommitDialog(QDialog): def __init__(self, repo, layername, _message = "", parent = None): super(CommitDialog, self).__init__(parent) self.repo = repo self.branch = None self.layername = layername self._message = _message or suggestedMessage self.message = None self.initGui() def initGui(self): self.setObjectName("CommitDialog") self.resize(600, 250) self.setWindowTitle("Syncronize layer to repository branch") self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(5) self.branchLabel = QLabel("Branch") self.verticalLayout.addWidget(self.branchLabel) self.branchCombo = QComboBox() self.branches = [] branches = self.repo.branches() for branch in branches: trees = self.repo.trees(branch) if self.layername in trees: self.branches.append(branch) self.branchCombo.addItems(self.branches) try: idx = self.branches.index("master") except: idx = 0 self.branchCombo.setCurrentIndex(idx) self.verticalLayout.addWidget(self.branchCombo) self.msgLabel = QLabel("Message to describe this update") self.verticalLayout.addWidget(self.msgLabel) self.text = QPlainTextEdit() self.text.setPlainText(self._message) self.verticalLayout.addWidget(self.text) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) self.verticalLayout.addWidget(self.buttonBox) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(bool(self.branches)) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.text.setFocus() def okPressed(self): self.branch = self.branchCombo.currentText() self.message = self.text.toPlainText() or datetime.now().strftime("%Y-%m-%d %H_%M_%S") self.close()
class CreateElectorateDialog(QDialog): """ Custom dialog for entering properties for a new electorate """ def __init__(self, registry: LinzElectoralDistrictRegistry, context: LinzRedistrictingContext, parent=None): super().__init__(parent) self.existing_names = list(registry.district_titles().keys()) self.existing_codes = [ f['code'] for f in registry.source_layer.getFeatures() ] self.setWindowTitle( self.tr('Create New {} Electorate').format( context.get_name_for_current_task())) dialog_layout = QVBoxLayout() label = QLabel( self.tr('Enter name for new {} electorate:').format( context.get_name_for_current_task())) dialog_layout.addWidget(label) self.name_line_edit = QLineEdit() self.name_line_edit.setPlaceholderText('Electorate name') dialog_layout.addWidget(self.name_line_edit) label = QLabel(self.tr('Enter code for new electorate:')) dialog_layout.addWidget(label) self.code_line_edit = QLineEdit() self.code_line_edit.setPlaceholderText('Electorate code') dialog_layout.addWidget(self.code_line_edit) self.feedback_label = QLabel() dialog_layout.addWidget(self.feedback_label) self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) dialog_layout.addWidget(self.button_box) self.button_box.rejected.connect(self.reject) self.button_box.accepted.connect(self.accept) self.name_line_edit.textChanged.connect(self.name_changed) self.code_line_edit.textChanged.connect(self.code_changed) self.setLayout(dialog_layout) self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) def name_changed(self): """ Triggered on name change """ self.__update_feedback_label() def code_changed(self): """ Triggered on code change """ self.__update_feedback_label() def __update_feedback_label(self): """ Updates the dialog feedback label """ name = self.name_line_edit.text().strip() code = self.code_line_edit.text().strip() self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) if name in self.existing_names: self.feedback_label.setText( self.tr('An electorate with this name already exists!')) elif not name: self.feedback_label.setText( self.tr('An electorate name must be entered!')) elif code in self.existing_codes: self.feedback_label.setText( self.tr('An electorate with this code already exists!')) elif not code: self.feedback_label.setText( self.tr('An electorate code must be entered!')) else: self.feedback_label.setText('') self.button_box.button(QDialogButtonBox.Ok).setEnabled(True) def name(self) -> str: """ Returns the current name entered in the dialog """ return self.name_line_edit.text() def code(self) -> str: """ Returns the current code entered in the dialog """ return self.code_line_edit.text()
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 MappingDialog(QDialog): """construct the mapping GUI""" targetTypes = [] importTypes = [] layerType = [] labels = {} comboBoxesType = {} comboBoxesLayer = {} comboBoxesLayerType = {} nextButton = None prevButton = None def __init__(self, parent=None): super(MappingDialog, self).__init__(parent) self.setWindowTitle("Maak een mapping t.b.v. het importeren") self.qlayout = QGridLayout(self) self.setWindowFlag(Qt.WindowCloseButtonHint, False) self.buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) self.nextButton = QPushButton() self.nextButton.setText("Volgende") self.prevButton = QPushButton() self.prevButton.setText("Vorige") self.label_laag = QLabel(self) self.label_laag.setText("Importeer in laag") self.label_types = QLabel(self) self.label_types.setText("Import types in bestand") self.label_conversie = QLabel(self) self.label_conversie.setText("Conversie naar type laag") self.label_target = QLabel(self) self.label_target.setText("Converteer naar type") self.qlayout.addWidget(self.label_types, 0, 0) self.qlayout.addWidget(self.label_conversie, 0, 1) self.qlayout.addWidget(self.label_laag, 0, 2) self.qlayout.addWidget(self.label_target, 0, 3) self.load_types() def load_types(self): i = 1 for importType in self.importTypes: try: self.comboBoxesLayer[importType].setEnabled(False) except: # pylint: disable=bare-except pass self.labels[i] = QLabel(self) self.labels[i].setText(importType) self.comboBoxesLayerType[importType] = QComboBox(self) self.comboBoxesLayerType[importType].addItems(self.layerType) self.qlayout.addWidget(self.labels[i], i, 0) self.qlayout.addWidget(self.comboBoxesLayerType[importType], i, 1) self.comboBoxesLayerType[importType].setEnabled(False) i += 1 self.qlayout.addWidget(self.nextButton, i, 1) self.qlayout.addWidget(self.prevButton, i, 0) self.qlayout.addWidget(self.buttons, i + 1, 0) self.set_buttons(False, True, None, self.load_layertype, False) def load_layertype(self): i = 1 for importType in self.comboBoxesLayerType: try: self.comboBoxesType[importType].setEnabled(False) except: # pylint: disable=bare-except pass self.comboBoxesLayerType[importType].setEnabled(False) self.comboBoxesLayer[importType] = QComboBox(self) layerType = self.comboBoxesLayerType[importType].currentText() layerNames = self.targetTypes[layerType].keys() self.comboBoxesLayer[importType].addItems(layerNames) self.qlayout.addWidget(self.comboBoxesLayer[importType], i, 2) i += 1 self.set_buttons(True, True, self.load_types, self.load_targettypes, False) def load_targettypes(self): i = 1 for importType in self.comboBoxesLayer: self.comboBoxesLayer[importType].setEnabled(False) self.comboBoxesType[importType] = QComboBox(self) layerType = self.comboBoxesLayerType[importType].currentText() layerName = self.comboBoxesLayer[importType].currentText() types = self.targetTypes[layerType][layerName] self.comboBoxesType[importType].addItems(types) self.qlayout.addWidget(self.comboBoxesType[importType], i, 3) i += 1 self.set_buttons(True, False, self.load_layertype, None, True) def set_buttons(self, prev, nxt, conPrev, conNext, okBtn): try: self.prevButton.clicked.disconnect() except: # pylint: disable=bare-except pass try: self.nextButton.clicked.disconnect() except: # pylint: disable=bare-except pass self.prevButton.setEnabled(prev) self.nextButton.setEnabled(nxt) if conPrev: self.prevButton.clicked.connect(conPrev) if conNext: self.nextButton.clicked.connect(conNext) self.buttons.button(QDialogButtonBox.Ok).setEnabled(okBtn) @staticmethod def getMapping(parent=None): """initiate the GUI and redirect the input""" mapping = {} dialog = MappingDialog(parent) result = dialog.exec_() for importType in dialog.importTypes: try: convType = dialog.comboBoxesLayerType[importType].currentText() except: # pylint: disable=bare-except convType = None try: convLayer = dialog.comboBoxesLayer[importType].currentText() except: # pylint: disable=bare-except convLayer = None try: convTargetType = dialog.comboBoxesType[importType].currentText( ) except: # pylint: disable=bare-except convTargetType = None mapping.update({ importType: { "convType": convType, "layerName": convLayer, "targetType": convTargetType } }) return (mapping, result == QDialog.Accepted)
class LoadInputsDialog(QDialog): """ Dialog to browse zipped input files """ loading_canceled = pyqtSignal(QDialog) loading_completed = pyqtSignal(QDialog) def __init__(self, drive_engine_dlg, zip_filepath, iface, parent=None, mode=None): super().__init__(parent) self.drive_engine_dlg = drive_engine_dlg self.zip_filepath = zip_filepath self.iface = iface self.mode = mode ini_str = self.get_ini_str(self.zip_filepath) self.multi_peril_csv_dict = self.get_multi_peril_csv_dict(ini_str) self.setWindowTitle('Load peril data from csv') self.peril_gbx = QGroupBox('Peril') self.peril_vlayout = QVBoxLayout() self.perils = self.multi_peril_csv_dict.keys() self.peril_gbx.setLayout(self.peril_vlayout) for peril in self.perils: chk = QCheckBox(peril) chk.setChecked(True) self.peril_vlayout.addWidget(chk) self.higher_on_top_chk = QCheckBox('Render higher values on top') self.higher_on_top_chk.setChecked(False) self.button_box = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.ok_button = self.button_box.button(QDialogButtonBox.Ok) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) vlayout = QVBoxLayout() vlayout.addWidget(self.peril_gbx) vlayout.addWidget(self.higher_on_top_chk) vlayout.addWidget(self.button_box) self.setLayout(vlayout) @staticmethod def get_ini_str(filepath): zfile = zipfile.ZipFile(filepath) for fname in zfile.namelist(): if os.path.splitext(fname)[1] == '.ini': ini_str = zfile.open( zfile.NameToInfo[fname]).read().decode('utf8') break return ini_str @staticmethod def get_multi_peril_csv_dict(ini_str): config = configparser.ConfigParser(allow_no_value=True) config.read_string(ini_str) multi_peril_csv_str = None for key in config: if 'multi_peril_csv' in config[key]: multi_peril_csv_str = config[key]['multi_peril_csv'] break if multi_peril_csv_str is None: raise KeyError('multi_peril_csv not found in .ini file') multi_peril_csv_dict = json.loads( multi_peril_csv_str.replace('\'', '"')) return multi_peril_csv_dict def load_from_csv(self, csv_path, peril): # extract the name of the csv file and remove the extension layer_name, ext = os.path.splitext(os.path.basename(csv_path)) wkt_field = None headers = get_headers(csv_path) for header in headers: if header.lower() in GEOM_FIELDNAMES: wkt_field = header break if self.mode == 'testing': add_to_legend = False else: add_to_legend = True try: layer = import_layer_from_csv( self, csv_path, layer_name, self.iface, wkt_field=wkt_field, add_to_legend=add_to_legend, add_on_top=True, zoom_to_layer=True) except RuntimeError as exc: log_msg(str(exc), level='C', message_bar=self.iface.messageBar(), exception=exc) raise exc if self.mode == 'testing': root = QgsProject.instance().layerTreeRoot() root.insertLayer(0, layer) self.iface.setActiveLayer(layer) self.iface.zoomToActiveLayer() if 'intensity' in [field.name() for field in layer.fields()]: LoadOutputAsLayerDialog.style_maps( layer, 'intensity', self.iface, 'input', render_higher_on_top=self.higher_on_top_chk.isChecked()) user_params = {'peril': peril} write_metadata_to_layer( self.drive_engine_dlg, 'input', layer, user_params) log_msg('Layer %s was loaded successfully' % layer_name, level='S', message_bar=self.iface.messageBar()) def accept(self): super().accept() for chk in self.peril_gbx.findChildren(QCheckBox): if chk.isChecked(): peril = chk.text() zfile = zipfile.ZipFile(self.zip_filepath) inner_path = 'input/' + self.multi_peril_csv_dict[peril] extracted_csv_path = zfile.extract( inner_path, path=os.path.dirname(self.zip_filepath)) self.load_from_csv(extracted_csv_path, peril) self.loading_completed.emit(self) def reject(self): super().reject() self.loading_canceled.emit(self)
class ProgressDialog(QDialog): """ Progress dialog shows progress bar for algorithm. """ def __init__(self, iface): QDialog.__init__(self, iface.mainWindow()) self.workerThread = None self.state = False self.resultStatus = None self.doReRun = False self.wasCanceled = False self.wasSuccessful = False self.savedProj = None self.result = None self.messageTxt = { 'msg_optimierung': self.tr('Berechnung der optimalen Stuetzenpositionen...'), 'msg_seillinie': self.tr('Berechnung der optimale Seillinie...') } # Build GUI Elements self.setWindowTitle(self.tr("SEILAPLAN wird ausgefuehrt")) self.resize(500, 100) self.container = QVBoxLayout() self.progressBar = QProgressBar(self) self.progressBar.setMinimumWidth(500) self.statusLabel = QLabel(self) self.hbox = QHBoxLayout() self.cancelButton = QDialogButtonBox() self.closeButton = QDialogButtonBox() self.resultLabel = QLabel(self) self.resultLabel.setMaximumWidth(500) self.resultLabel.setSizePolicy( QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)) self.resultLabel.setWordWrap(True) spacer1 = QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Fixed) self.rerunButton = QPushButton(self.tr("zurueck zum Startfenster")) self.rerunButton.setVisible(False) spacer2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.cancelButton.setStandardButtons(QDialogButtonBox.Cancel) self.cancelButton.button(QDialogButtonBox.Cancel).setText(self.tr("Abbrechen")) self.cancelButton.clicked.connect(self.onAbort) self.closeButton.setStandardButtons(QDialogButtonBox.Close) self.closeButton.button(QDialogButtonBox.Close).setText(self.tr("Schliessen")) self.closeButton.clicked.connect(self.onClose) self.hbox.addWidget(self.rerunButton) self.hbox.addItem(spacer2) self.hbox.addWidget(self.cancelButton) self.hbox.setAlignment(self.cancelButton, Qt.AlignHCenter) self.hbox.addWidget(self.closeButton) self.hbox.setAlignment(self.closeButton, Qt.AlignHCenter) self.closeButton.hide() self.container.addWidget(self.progressBar) self.container.addWidget(self.statusLabel) self.container.addWidget(self.resultLabel) self.container.addItem(spacer1) self.container.addLayout(self.hbox) self.container.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(self.container) # noinspection PyMethodMayBeStatic def tr(self, message, **kwargs): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString Parameters ---------- **kwargs """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate(type(self).__name__, message) def setThread(self, workerThread): self.workerThread = workerThread self.connectThreadSignals() def connectThreadSignals(self): # Connect signals of thread self.workerThread.sig_jobEnded.connect(self.jobEnded) self.workerThread.sig_jobError.connect(self.onError) self.workerThread.sig_value.connect(self.valueFromThread) self.workerThread.sig_range.connect(self.rangeFromThread) self.workerThread.sig_text.connect(self.textFromThread) self.workerThread.sig_result.connect(self.resultFromThread) self.rerunButton.clicked.connect(self.onRerun) def run(self): # Show modal dialog window (QGIS is still responsive) self.show() # start event loop self.exec() def jobEnded(self, success): self.setWindowTitle("SEILAPLAN") if success: self.progressBar.setValue(self.progressBar.maximum()) self.wasSuccessful = True # Close progress dialog so that adjustment window can be opened self.close() else: # If there was an abort by the user self.statusLabel.setText(self.tr("Berechnungen abgebrochen.")) self.progressBar.setValue(self.progressBar.minimum()) self.finallyDo() def valueFromThread(self, value): self.progressBar.setValue(int(value)) def rangeFromThread(self, range_vals): self.progressBar.setRange(int(round(range_vals[0])), int(round(range_vals[1]))) def maxFromThread(self, max): self.progressBar.setValue(self.progressBar.maximum()) def textFromThread(self, message): self.statusLabel.setText(self.messageTxt[message]) def resultFromThread(self, resultStatus): self.resultStatus = resultStatus # resultStatus: # 1 = Optimization successful # 2 = Cable takes off from support # 3 = Optimization partially successful def onAbort(self): self.setWindowTitle('SEILAPLAN') self.statusLabel.setText(self.tr( 'Laufender Prozess wird abgebrochen...')) self.workerThread.cancel() # Terminates process cleanly self.wasCanceled = True def onError(self, exception_string): self.setWindowTitle(self.tr('SEILAPLAN: Berechnung fehlgeschlagen')) self.statusLabel.setText(self.tr('Ein Fehler ist aufgetreten:')) self.resultLabel.setText(self.tr(exception_string)) self.resultLabel.setHidden(False) self.progressBar.setValue(self.progressBar.minimum()) self.setLayout(self.container) self.finallyDo() def onRerun(self): self.doReRun = True self.onClose() def finallyDo(self): self.rerunButton.setVisible(True) self.cancelButton.hide() self.closeButton.show() def onClose(self): self.close()
def __init__(self, parent, confHandler): """ :type confHandler: configHandler.ConfigHandler """ QDialog.__init__(self, parent) self.confHandler = confHandler self.doSave = False self.setWindowTitle(self.tr('Output Optionen')) main_widget = QWidget(self) # Build up gui # Project title hbox1 = QHBoxLayout() projectNameLabel = QLabel(self.tr('Projektname')) projectNameLabel.setMinimumWidth(100) self.projectField = QLineEdit() self.projectField.setMinimumWidth(400) self.projectField.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)) hbox1.addWidget(projectNameLabel) hbox1.addWidget(self.projectField) # Save path hbox2 = QHBoxLayout() saveLabel = QLabel(self.tr('Speicherpfad')) saveLabel.setMinimumWidth(100) self.pathField = QComboBox() self.pathField.setMinimumWidth(400) self.pathField.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)) openButton = QPushButton() openButton.setMaximumSize(QSize(27, 27)) icon = QIcon() iconPath = os.path.join(os.path.dirname(__file__), 'icons', 'icon_open.png') icon.addPixmap(QPixmap(iconPath), QIcon.Normal, QIcon.Off) openButton.setIcon(icon) openButton.setIconSize(QSize(24, 24)) openButton.clicked.connect(self.onOpenDialog) hbox2.addWidget(saveLabel) hbox2.addWidget(self.pathField) hbox2.addWidget(openButton) # Create checkboxes questionLabel = QLabel( self.tr('Welche Produkte sollen erzeugt werden?')) self.checkBoxShortReport = QCheckBox(self.tr('Kurzbericht')) self.checkBoxReport = QCheckBox(self.tr('Technischer Bericht')) self.checkBoxPlot = QCheckBox(self.tr('Diagramm')) self.checkBoxGeodata = QCheckBox( self.tr('Shape-Daten der Stuetzen und Seillinie')) self.checkBoxKML = QCheckBox( self.tr('KML-Daten der Stuetzen und Seillinie')) self.checkBoxCoords = QCheckBox( self.tr('Koordinaten-Tabellen der Stuetzen und Seillinie')) # Set tick correctly self.checkBoxShortReport.setChecked( self.confHandler.outputOptions['shortReport']) self.checkBoxReport.setChecked( self.confHandler.outputOptions['report']) self.checkBoxPlot.setChecked(self.confHandler.outputOptions['plot']) self.checkBoxGeodata.setChecked( self.confHandler.outputOptions['geodata']) self.checkBoxKML.setChecked(self.confHandler.outputOptions['kml']) self.checkBoxCoords.setChecked( self.confHandler.outputOptions['coords']) # Create Ok/Cancel Button and connect signal buttonBox = QDialogButtonBox(main_widget) buttonBox.setStandardButtons(QDialogButtonBox.Save | QDialogButtonBox.Cancel) buttonBox.button(QDialogButtonBox.Save).setText(self.tr("Speichern")) buttonBox.button(QDialogButtonBox.Cancel).setText(self.tr("Abbrechen")) buttonBox.button(QDialogButtonBox.Cancel).clicked.connect( self.onCancel) buttonBox.button(QDialogButtonBox.Save).clicked.connect(self.onSave) # Layout container = QVBoxLayout(main_widget) container.addLayout(hbox1) container.addLayout(hbox2) container.addWidget(QLabel('')) container.addWidget(questionLabel) container.addWidget(self.checkBoxShortReport) container.addWidget(self.checkBoxReport) container.addWidget(self.checkBoxPlot) container.addWidget(self.checkBoxGeodata) container.addWidget(self.checkBoxKML) container.addWidget(self.checkBoxCoords) container.addWidget(buttonBox) container.setAlignment(Qt.AlignLeft) self.setLayout(container) self.fillInData()
class AdminUnitSelector(QDialog): """ Generic admin unit manager dialog. """ def __init__(self, parent=None): QDialog.__init__(self, parent) self.resize(400, 410) self.verticalLayout = QVBoxLayout(self) self.adminUnitManager = AdminUnitManager(self) self.verticalLayout.addWidget(self.adminUnitManager) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Close | QDialogButtonBox.Ok) self.verticalLayout.addWidget(self.buttonBox) self.selectedAdminUnit = None # Connect signals self.adminUnitManager.stateChanged.connect(self.onStateChanged) self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect( self.onAcceptDialog) self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect( self.onRejectDialog) self.buttonBox.button(QDialogButtonBox.Close).clicked.connect( self.onRejectDialog) def setManageMode(self, enableManage): """ :param enableManage: True to set the selector to manage mode or false to disable. """ if enableManage: self.adminUnitManager.setState(MANAGE) else: self.adminUnitManager.setState(VIEW) def onStateChanged(self, isManageMode): ''' Slot raised when the state of the admin unit manager widget changes ''' if isManageMode: self.buttonBox.button(QDialogButtonBox.Ok).setVisible(False) self.buttonBox.button(QDialogButtonBox.Cancel).setVisible(False) self.buttonBox.button(QDialogButtonBox.Close).setVisible(True) title = self.tr('Manage Administrative Units') else: self.buttonBox.button(QDialogButtonBox.Ok).setVisible(True) self.buttonBox.button(QDialogButtonBox.Cancel).setVisible(True) self.buttonBox.button(QDialogButtonBox.Close).setVisible(False) title = self.tr('Select Administrative Unit') self.setWindowTitle(title) def onAcceptDialog(self): ''' Slot raised on accepting administrative unit selection. This is raised when the dialog is in VIEW mode. ''' self.adminUnitManager.notificationBar().clear() self.selectedAdminUnit = self.adminUnitManager.selectedAdministrativeUnit( ) if self.selectedAdminUnit is None: msg = self.tr('Please select an administrative unit ' 'from the list.') self.adminUnitManager.notificationBar().insertWarningNotification( msg) else: self.accept() def onRejectDialog(self): ''' Slot raised to close the dialog. ''' self.reject()