def testLinkProjectColor(self): """ Test linking to a project color """ project_scheme = [s for s in QgsApplication.colorSchemeRegistry().schemes() if isinstance(s, QgsProjectColorScheme)][0] project_scheme.setColors([[QColor(255, 0, 0), 'col1'], [QColor(0, 255, 0), 'col2']]) button = QgsColorButton() spy = QSignalSpy(button.unlinked) button.setColor(QColor(0, 0, 255)) self.assertFalse(button.linkedProjectColorName()) button.linkToProjectColor('col1') self.assertEqual(button.linkedProjectColorName(), 'col1') self.assertEqual(button.color().name(), '#ff0000') self.assertEqual(len(spy), 0) button.unlink() self.assertFalse(button.linkedProjectColorName()) self.assertEqual(button.color().name(), '#0000ff') self.assertEqual(len(spy), 1) button.linkToProjectColor('col2') self.assertEqual(button.linkedProjectColorName(), 'col2') self.assertEqual(button.color().name(), '#00ff00') self.assertEqual(len(spy), 1) project_scheme.setColors([[QColor(255, 0, 0), 'xcol1'], [QColor(0, 255, 0), 'xcol2']]) # linked color no longer exists self.assertFalse(button.linkedProjectColorName()) self.assertEqual(button.color().name(), '#0000ff') self.assertEqual(len(spy), 2)
def testClearingColors(self): """ Test setting colors to transparent """ # start with a valid color button = QgsColorButton() button.setAllowAlpha(True) button.setColor(QColor(255, 100, 200, 255)) self.assertEqual(button.color(), QColor(255, 100, 200, 255)) # now set to no color button.setToNoColor() # ensure that only the alpha channel has changed - not the other color components self.assertEqual(button.color(), QColor(255, 100, 200, 0))
def testClearingColors(self): """ Test setting colors to transparent """ # start with a valid color button = QgsColorButton() button.setAllowOpacity(True) button.setColor(QColor(255, 100, 200, 255)) self.assertEqual(button.color(), QColor(255, 100, 200, 255)) # now set to no color button.setToNoColor() # ensure that only the alpha channel has changed - not the other color components self.assertEqual(button.color(), QColor(255, 100, 200, 0))
def testLinkProjectColor(self): """ Test linking to a project color """ project_scheme = [ s for s in QgsApplication.colorSchemeRegistry().schemes() if isinstance(s, QgsProjectColorScheme) ][0] project_scheme.setColors([[QColor(255, 0, 0), 'col1'], [QColor(0, 255, 0), 'col2']]) button = QgsColorButton() spy = QSignalSpy(button.unlinked) button.setColor(QColor(0, 0, 255)) self.assertFalse(button.linkedProjectColorName()) button.linkToProjectColor('col1') self.assertEqual(button.linkedProjectColorName(), 'col1') self.assertEqual(button.color().name(), '#ff0000') self.assertEqual(len(spy), 0) button.unlink() self.assertFalse(button.linkedProjectColorName()) self.assertEqual(button.color().name(), '#0000ff') self.assertEqual(len(spy), 1) button.linkToProjectColor('col2') self.assertEqual(button.linkedProjectColorName(), 'col2') self.assertEqual(button.color().name(), '#00ff00') self.assertEqual(len(spy), 1) project_scheme.setColors([[QColor(255, 0, 0), 'xcol1'], [QColor(0, 255, 0), 'xcol2']]) # linked color no longer exists self.assertFalse(button.linkedProjectColorName()) self.assertEqual(button.color().name(), '#0000ff') self.assertEqual(len(spy), 2)
class SnailTabSettingsSystem(QtCore.QObject): def __init__(self, parent, widget): super(SnailTabSettingsSystem, self).__init__() self.parent = parent self._widget = widget self.init_gui() def init_gui(self): self._cpu_color = QgsColorButton() self._widget.mCpuLayout.addWidget(self._cpu_color) self._ram_color = QgsColorButton() self._widget.mRamLayout.addWidget(self._ram_color) self._background_color = QgsColorButton() self._widget.mBackgroundLayout.addWidget(self._background_color) self._axes_color = QgsColorButton() self._widget.mAxesLayout.addWidget(self._axes_color) setting = SnailSettings.System.RefreshSec self._widget.mRefreshSec.setMinimum(1) sec = SnailSettings.get(setting, 1, int) self._widget.mRefreshSec.setValue(sec) setting = SnailSettings.System.RamWarning activated = SnailSettings.get(setting, False, bool) self._widget.mRamWarning.setChecked(activated) setting = SnailSettings.System.RamWarningLimit limit = SnailSettings.get(setting, 90, int) self._widget.mRamWarningLimit.setValue(limit) self.read_settings() def read_settings(self): setting = SnailSettings.System.DisplayChart display_chart = SnailSettings.get(setting, True, bool) checkbox = self._widget.mSystemDisplayChart checkbox.setChecked(display_chart) setting = SnailSettings.System.CpuColor color = SnailSettings.get(setting, QtGui.QColor("blue")) self._cpu_color.setColor(QtGui.QColor(color)) setting = SnailSettings.System.RamColor color = SnailSettings.get(setting, QtGui.QColor("red")) self._ram_color.setColor(QtGui.QColor(color)) setting = SnailSettings.System.BackgroundColor color = SnailSettings.get(setting, QtGui.QColor("white")) self._background_color.setColor(QtGui.QColor(color)) setting = SnailSettings.System.AxisColor color = SnailSettings.get(setting, QtGui.QColor("grey")) self._axes_color.setColor(QtGui.QColor(color)) def store(self): checkbox = self._widget.mSystemDisplayChart setting = SnailSettings.System.DisplayChart SnailSettings.set(setting, checkbox.isChecked()) color = self._cpu_color.color().name() setting = SnailSettings.System.CpuColor SnailSettings.set(setting, color) color = self._ram_color.color().name() setting = SnailSettings.System.RamColor SnailSettings.set(setting, color) color = self._background_color.color().name() setting = SnailSettings.System.BackgroundColor SnailSettings.set(setting, color) color = self._axes_color.color().name() setting = SnailSettings.System.AxisColor SnailSettings.set(setting, color) sec = self._widget.mRefreshSec.value() setting = SnailSettings.System.RefreshSec SnailSettings.set(setting, sec) activated = self._widget.mRamWarning.isChecked() setting = SnailSettings.System.RamWarning SnailSettings.set(setting, activated) limit = self._widget.mRamWarningLimit.value() setting = SnailSettings.System.RamWarningLimit SnailSettings.set(setting, limit) @property def display_chart(self): return self._widget.mSystemDisplayChart.isChecked() @display_chart.setter def display_chart(self, display): pass @property def axes_color(self): return self._axes_color.color().name() @axes_color.setter def axes_color(self, color): pass @property def background_color(self): return self._background_color.color().name() @background_color.setter def background_color(self, color): pass @property def cpu_color(self): return self._cpu_color.color().name() @cpu_color.setter def cpu_color(self, color): pass @property def ram_color(self): return self._ram_color.color().name() @ram_color.setter def ram_color(self, color): pass
class TrackWidget(QWidget, Ui_Track): def __init__(self, parent=None): super(TrackWidget, self).__init__(parent) self.setupUi(self) self.title = "Display track" self.canvas = None self.band = None self.color_btn = None self.center = False self.position = None self.geom_type = None self.marker = None self.hidden = False self.centerButton.setEnabled(False) icon = QIcon(":/resources/mActionSave.svg") self.save_track_pushButton.setIcon(icon) self.save_track_pushButton.setToolTip("Save Track") self.save_track_pushButton.clicked.connect(self.save_track) def init(self, title, canvas, default_color, geom_type, marker): self.canvas = canvas self.geom_type = geom_type self.track_groupBox.setTitle(title) if marker: # Add marker self.marker = marker self.with_marker = True else: self.with_marker = False # Add rubber band self.band = QgsRubberBand(self.canvas, self.geom_type) if self.geom_type == QgsWkbTypes.PointGeometry: self.band.setIcon(QgsRubberBand.ICON_CIRCLE) self.band.setIconSize(12) else: self.band.setWidth(3) # Add color button widget for picking color self.color_btn = QgsColorButton() self.horizontal_layout_color.insertWidget(1, self.color_btn, 0, Qt.AlignLeft) self.color_btn.colorChanged.connect(self.color_changed) self.color_btn.setDefaultColor(default_color) self.color_btn.setColor(default_color) # Set signals self.centerButton.clicked.connect(self.center_to_location) self.clearTrackButton.clicked.connect(self.clear_track) def color_changed(self): transparent_color = QColor(self.color_btn.color()) transparent_color.setAlpha(80) self.band.setColor(transparent_color) if self.with_marker: self.marker.set_color(QColor(self.color_btn.color())) def add_position(self, position): self.band.addPoint(position) def track_update_canvas(self, position, heading): self.centerButton.setEnabled(True) self.position = position self.add_position(position) if self.with_marker: self.marker.set_center(position, heading) if self.isHidden(): if self.with_marker: self.marker.hide() self.band.hide() else: if self.with_marker: self.marker.show() self.band.show() def center_to_location(self): """ Center to last received position on the map. """ rect = QgsRectangle(self.position, self.position) self.canvas.setExtent(rect) self.canvas.zoomScale(400) self.canvas.refresh() def hide_band(self): self.band.hide() def hide_marker(self): if self.with_marker: self.marker.hide() def clear_track(self): self.band.reset(self.geom_type) def save_track(self): """ Save the track to disk """ layer_name, selected_filter = QFileDialog.getSaveFileName(None, 'Save Track', "", 'Shapefile (*.shp);;KML (*.kml);;GPX (*.gpx)') if layer_name != '': if self.geom_type == QgsWkbTypes.PointGeometry: geometric_object = "MultiPoint?crs=epsg:4326" else: geometric_object = "LineString?crs=epsg:4326" layer = QgsVectorLayer( geometric_object, layer_name, "memory") feature = QgsFeature() feature.setGeometry(self.band.asGeometry()) layer.dataProvider().addFeatures([feature]) if selected_filter == "Shapefile (*.shp)": if not layer_name.endswith('.shp'): layer_name = layer_name + '.shp' ret = QgsVectorFileWriter.writeAsVectorFormat(layer, layer_name, "utf-8", QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId), "ESRI Shapefile") if ret == QgsVectorFileWriter.NoError: logger.info(layer.name() + " saved to " + layer_name) elif selected_filter == "KML (*.kml)": if not layer_name.endswith('.kml'): layer_name = layer_name + '.kml' QgsVectorFileWriter.writeAsVectorFormat(layer, layer_name, "utf-8", QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId), "KML") elif selected_filter == "GPX (*.gpx)": if not layer_name.endswith('.gpx'): layer_name = layer_name + '.gpx' ds_options = list() ds_options.append("GPX_USE_EXTENSIONS=TRUE") QgsVectorFileWriter.writeAsVectorFormat(layer, layer_name, "utf-8", QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId), "GPX", datasourceOptions=ds_options) def close(self): self.hide_band() self.hide_marker()
class QgsTextAnnotationDialog(QDialog): def __init__(self, item): QDialog.__init__(self) self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName(("gridLayout")) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(("horizontalLayout")) self.mFontComboBox = QFontComboBox(self) self.mFontComboBox.setObjectName(("mFontComboBox")) self.horizontalLayout.addWidget(self.mFontComboBox) spacerItem = QSpacerItem(38, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.mFontSizeSpinBox = QSpinBox(self) self.mFontSizeSpinBox.setObjectName(("mFontSizeSpinBox")) self.horizontalLayout.addWidget(self.mFontSizeSpinBox) self.mBoldPushButton = QPushButton(self) self.mBoldPushButton.setMinimumSize(QSize(50, 0)) self.mBoldPushButton.setCheckable(True) self.mBoldPushButton.setObjectName(("mBoldPushButton")) self.horizontalLayout.addWidget(self.mBoldPushButton) self.mItalicsPushButton = QPushButton(self) self.mItalicsPushButton.setMinimumSize(QSize(50, 0)) self.mItalicsPushButton.setCheckable(True) self.mItalicsPushButton.setObjectName(("mItalicsPushButton")) self.horizontalLayout.addWidget(self.mItalicsPushButton) self.mFontColorButton = QgsColorButton(self) self.mFontColorButton.setText(("")) self.mFontColorButton.setAutoDefault(False) self.mFontColorButton.setObjectName(("mFontColorButton")) self.horizontalLayout.addWidget(self.mFontColorButton) self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) self.mButtonBox = QDialogButtonBox(self) self.mButtonBox.setOrientation(Qt.Horizontal) self.mButtonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.mButtonBox.setObjectName(("mButtonBox")) self.gridLayout.addWidget(self.mButtonBox, 3, 0, 1, 1) self.mTextEdit = QTextEdit(self) self.mTextEdit.setObjectName(("mTextEdit")) self.gridLayout.addWidget(self.mTextEdit, 1, 0, 1, 1) self.mStackedWidget = QStackedWidget(self) self.mStackedWidget.setObjectName(("mStackedWidget")) self.page = QWidget() self.page.setObjectName(("page")) self.mStackedWidget.addWidget(self.page) self.page_2 = QWidget() self.page_2.setObjectName(("page_2")) self.mStackedWidget.addWidget(self.page_2) self.gridLayout.addWidget(self.mStackedWidget, 2, 0, 1, 1) self.setLayout(self.gridLayout) self.mStackedWidget.setCurrentIndex(0) QObject.connect(self.mButtonBox, SIGNAL(("accepted()")), self.accept) QObject.connect(self.mButtonBox, SIGNAL(("rejected()")), self.reject) self.setTabOrder(self.mFontComboBox, self.mFontSizeSpinBox) self.setTabOrder(self.mFontSizeSpinBox, self.mBoldPushButton) self.setTabOrder(self.mBoldPushButton, self.mItalicsPushButton) self.setTabOrder(self.mItalicsPushButton, self.mFontColorButton) self.setTabOrder(self.mFontColorButton, self.mTextEdit) self.setTabOrder(self.mTextEdit, self.mButtonBox) self.setWindowTitle("Annotation text") self.mBoldPushButton.setText("B") self.mItalicsPushButton.setText("I") self.mTextDocument = None self.mItem = item self.mEmbeddedWidget = QgsAnnotationWidget(self, self.mItem ) self.mEmbeddedWidget.show() self.mStackedWidget.addWidget( self.mEmbeddedWidget ) self.mStackedWidget.setCurrentWidget( self.mEmbeddedWidget ) if ( self.mItem != None ): self.mTextDocument = self.mItem.document() self.mTextEdit.setDocument( self.mTextDocument ) self.mFontColorButton.setColorDialogTitle( "Select font color" ) self.mFontColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel ) self.setCurrentFontPropertiesToGui() QObject.connect( self.mButtonBox, SIGNAL("accepted()"), self.applyTextToItem) # QObject.connect( self.mFontComboBox, SIGNAL( "currentFontChanged(QFont())"), self.changeCurrentFormat) self.mFontComboBox.currentFontChanged.connect(self.changeCurrentFormat) QObject.connect( self.mFontSizeSpinBox, SIGNAL( "valueChanged( int )" ), self.changeCurrentFormat ) QObject.connect( self.mBoldPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat) QObject.connect( self.mItalicsPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat) QObject.connect( self.mTextEdit, SIGNAL( "cursorPositionChanged()" ), self.setCurrentFontPropertiesToGui ) # QObject.connect( self.mButtonBox, SIGNAL( "accepted()" ), self.applySettingsToItem) deleteButton = QPushButton( "Delete" ) QObject.connect( deleteButton, SIGNAL( "clicked()" ), self.deleteItem ) self.mButtonBox.addButton( deleteButton, QDialogButtonBox.RejectRole ) def applyTextToItem(self): if ( self.mItem != None and self.mTextDocument !=None ): if ( self.mEmbeddedWidget != None): self.mEmbeddedWidget.apply() self.mItem.setDocument( self.mTextDocument ) self.mItem.update() def changeCurrentFormat(self): newFont = QFont() newFont.setFamily( self.mFontComboBox.currentFont().family() ) #bold if ( self.mBoldPushButton.isChecked() ): newFont.setBold( True ) else: newFont.setBold( False ) #italic if ( self.mItalicsPushButton.isChecked() ): newFont.setItalic( True ) else: newFont.setItalic( False ) #size newFont.setPointSize( self.mFontSizeSpinBox.value() ) self.mTextEdit.setCurrentFont( newFont ) #color self.mTextEdit.setTextColor( self.mFontColorButton.color() ) def on_mFontColorButton_colorChanged(self, color ): self.changeCurrentFormat() def setCurrentFontPropertiesToGui(self): self.blockAllSignals( True ) currentFont = self.mTextEdit.currentFont() self.mFontComboBox.setCurrentFont( currentFont ) self.mFontSizeSpinBox.setValue( currentFont.pointSize() ) self.mBoldPushButton.setChecked( currentFont.bold() ) self.mItalicsPushButton.setChecked( currentFont.italic() ) self.mFontColorButton.setColor( self.mTextEdit.textColor() ) self.blockAllSignals( False ) def blockAllSignals(self, block ): self.mFontComboBox.blockSignals( block ) self.mFontSizeSpinBox.blockSignals( block ) self.mBoldPushButton.blockSignals( block ) self.mItalicsPushButton.blockSignals( block ) self.mFontColorButton.blockSignals( block ) def deleteItem(self): scene = self.mItem.scene() if ( scene != None ): scene.removeItem( self.mItem ) self.mItem = None
class BarValueConfigWidget(QWidget): """ Widget for editing y-value configurations. """ def __init__(self, parent=None, value_field='', def_color='#2564e1', legend_name=''): QWidget.__init__(self, parent) self._value_field = value_field # Insert controls for editing fill color and legend names self.lbl_fill_color = QLabel(self) self.lbl_fill_color.setText( QApplication.translate("ValueConfigWidget", "Fill color")) self.fill_color_btn = QgsColorButton( self, QApplication.translate("ValueConfigWidget", "Select bar fill color")) self.fill_color_btn.setMaximumHeight(30) self.fill_color_btn.setMinimumHeight(30) self.fill_color_btn.setMinimumWidth(100) if QColor.isValidColor(def_color): default_color = QColor(def_color) self.fill_color_btn.setColor(default_color) self.lbl_legend_name = QLabel(self) self.lbl_legend_name.setText( QApplication.translate("ValueConfigWidget", "Legend name")) self.txt_legend_name = QLineEdit(self) self.txt_legend_name.setMaxLength(50) self.txt_legend_name.setMinimumHeight(30) self.txt_legend_name.setText(legend_name) self.layout = QGridLayout(self) self.layout.addWidget(self.lbl_fill_color, 0, 0, 1, 1) self.layout.addWidget(self.fill_color_btn, 0, 1, 1, 1) self.layout.addWidget(self.lbl_legend_name, 1, 0, 1, 1) self.layout.addWidget(self.txt_legend_name, 1, 1, 1, 1) def value_field(self): """ :return: Returns the value field used from the referenced table. :rtype: str """ return self._value_field def set_value_field(self, value_field): """ Set the value field used from the referenced table. :param value_field: Value field used from the referenced table. :type value_field: str """ if value_field: self._value_field = value_field def configuration(self): """ :return: BarValueConfiguration settings. :rtype: BarValueConfiguration """ from stdm.composer.chart_configuration import BarValueConfiguration bar_value_config = BarValueConfiguration() bar_value_config.set_value_field(self._value_field) bar_value_config.set_fill_color(self.fill_color_btn.color().name()) bar_value_config.set_legend_name(self.txt_legend_name.text()) return bar_value_config def set_configuration(self, config): pass
class MatrixLayerDialog(QtWidgets.QDialog, FORM_CLASS): def __init__(self, parent=None, layerId=None): super(MatrixLayerDialog, self).__init__(parent) self.setupUi(self) self.project = parent.project self.proj = QgsProject.instance() self.tempLayerName = '' self.layerId = layerId self.labelColor = QLabel("Color") self.buttonColorRamp = QgsColorRampButton(self, 'Color Ramp') self.buttonColorRamp.hide() self.buttonColor = QgsColorButton(self, 'Color') self.buttonColor.hide() # Linking objects with controls self.help = self.findChild(QtWidgets.QPushButton, 'btn_help') self.layerName = self.findChild(QtWidgets.QLineEdit, 'layerName') self.expression = self.findChild(QtWidgets.QLineEdit, 'expression') self.baseScenario = self.findChild(QtWidgets.QComboBox, 'base_scenario') self.operators = self.findChild(QtWidgets.QComboBox, name='cb_operator') self.alternateScenario = self.findChild(QtWidgets.QComboBox, name='cb_alternate_scenario') self.method = self.findChild(QtWidgets.QComboBox, name='cb_method') self.originList = self.findChild(QtWidgets.QListWidget, name='lw_origin') self.originList.setSelectionMode( QtWidgets.QAbstractItemView.MultiSelection) self.destinationList = self.findChild(QtWidgets.QListWidget, name='lw_destination') self.destinationList.setSelectionMode( QtWidgets.QAbstractItemView.MultiSelection) self.filter = self.findChildren(QtWidgets.QLineEdit, name='filter') self.categories = self.findChild(QtWidgets.QListWidget, 'categories') self.scenarios = self.findChild(QtWidgets.QTreeView, 'scenarios') self.buttonBox = self.findChild(QtWidgets.QDialogButtonBox, 'buttonBox') self.progressBar = self.findChild(QtWidgets.QProgressBar, 'progressBar') # Control Actions self.help.clicked.connect(self.open_help) self.layerName.keyPressEvent = self.keyPressEvent self.buttonBox.accepted.connect(self.create_layer) self.operators.currentIndexChanged[int].connect(self.operator_changed) self.baseScenario.currentIndexChanged[int].connect( self.scenario_changed) self.categories.itemDoubleClicked.connect(self.category_selected) self.method.currentIndexChanged[int].connect(self.method_changed) # Controls settings self.alternateScenario.setEnabled(False) # Loads combo-box controls self.__load_operators() self.__load_scenarios_combobox() self.__load_zone_lists() self.__load_categories() self.__load_centroids() self.__reload_scenarios() self.method.setCurrentIndex(1) if self.layerId: self.__load_default_data() def open_help(self): """ @summary: Opens QTranus users help """ filename = "file:///" + os.path.join( os.path.dirname(os.path.realpath(__file__)) + "/userHelp/", 'matrix.html') webbrowser.open_new_tab(filename) def keyPressEvent(self, event): """ @summary: Detects when a key is pressed @param event: Key press event @type event: Event object """ QtWidgets.QLineEdit.keyPressEvent(self.layerName, event) if not self.validate_string(event.text()): messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Layer Name", "Invalid character: " + event.text() + ".", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() if self.layerName.isUndoAvailable(): self.layerName.setText(self.tempLayerName) else: self.tempLayerName = self.layerName.text() # Load data to edit the zones layer def __load_default_data(self): projectPath = self.project.shape[0:max(self.project.shape.rfind('\\'), self.project.shape.rfind('/'))] # Get data from XML File with the parameters expression, field, name, scenario, id_field_name, originZones, destinationZones, method, color = FileM.find_layer_data( projectPath, self.layerId) print(expression, field, name, scenario, id_field_name, originZones, destinationZones, method, color) scenario = scenario.split(",") scenario[0] = scenario[0].replace("'", "").replace("[", "").replace("]", "") self.layerName.setText(name) self.expression.setText(expression) indexMethod = self.method.findText(method, Qt.MatchFixedString) self.method.setCurrentIndex(indexMethod) indexBaseScenario = self.base_scenario.findText( scenario[0], Qt.MatchFixedString) self.base_scenario.setCurrentIndex(indexBaseScenario) if len(scenario) == 3: scenario[2] = scenario[2].replace("'", "").replace("]", "").strip() indexOperators = self.operators.findText(scenario[2], Qt.MatchFixedString) self.operators.setCurrentIndex(indexOperators) scenario[1] = scenario[1].replace("'", "").strip() indexAlternateScenario = self.alternateScenario.findText( scenario[1], Qt.MatchFixedString) self.alternateScenario.setCurrentIndex(indexAlternateScenario) originZones = originZones.replace("'", "").replace("[", "").replace( "]", "").replace(" ", "") originZones = originZones.split(",") destinationZones = destinationZones.replace("'", "").replace( "[", "").replace("]", "").replace(" ", "") destinationZones = destinationZones.split(",") for item in originZones: selectionOrigin = self.originList.findItems( item, Qt.MatchFixedString) indexOrigin = self.originList.indexFromItem(selectionOrigin[0]) self.originList.setCurrentIndex(indexOrigin) for item in destinationZones: selectionDestination = self.destinationList.findItems( item, Qt.MatchFixedString) indexDestination = self.destinationList.indexFromItem( selectionDestination[0]) self.destinationList.setCurrentIndex(indexDestination) if method == 'Size': qcolor = QColor() qcolor.setRgb(int(color)) self.buttonColor.setColor(qcolor) if method == 'Color': color = literal_eval(color) arrColor1 = color['color1'].split(",") arrColor2 = color['color2'].split(",") arrColor1 = list(map(lambda x: int(x), arrColor1)) arrColor2 = list(map(lambda x: int(x), arrColor2)) qcolor1 = QColor(arrColor1[0], arrColor1[1], arrColor1[2]) qcolor2 = QColor(arrColor2[0], arrColor2[1], arrColor2[2]) qColorRamp = QgsGradientColorRamp() qColorRamp.setColor1(qcolor1) qColorRamp.setColor2(qcolor2) self.buttonColorRamp.setColorRamp(qColorRamp) def method_changed(self, event): if self.method.currentText() == "Color": self.labelColor.setText("Color Ramp") self.formLayout = self.findChild(QFormLayout, 'formLayout_8') self.buttonColor.hide() self.buttonColorRamp.show() self.buttonColorRamp.setShowGradientOnly(True) self.formLayout.addRow(self.labelColor, self.buttonColorRamp) elif self.method.currentText() == "Size": self.labelColor.setText("Color") self.formLayout = self.findChild(QFormLayout, 'formLayout_8') self.buttonColorRamp.hide() self.buttonColor.show() self.formLayout.addRow(self.labelColor, self.buttonColor) def validate_string(self, input): """ @summary: Validates invalid characters @param input: Input string @type input: String object """ pattern = re.compile('[\\\/\:\*\?\"\<\>\|]') if re.match(pattern, input) is None: return True else: return False def __load_scenarios_combobox(self): """ @summary: Loads scenarios combo-box """ items = self.project.map_data.get_sorted_scenarios() self.base_scenario.addItems(items) def __load_alternate_scenario_combobox(self): """ @summary: Loads alternate scenario combo-box """ baseScenario = self.baseScenario.currentText() items = self.project.map_data.get_sorted_scenarios() for item in items: if item != baseScenario: self.alternateScenario.addItem(item) def scenario_changed(self, newIndex): """ @summary: Detects when an scenario was changed """ if self.operators.currentText() != '': self.alternateScenario.clear() self.__load_alternate_scenario_combobox() def operator_changed(self): """ @summary: Detects when an operator was changed """ currentOperator = self.operators.currentText() if self.operators.currentText() == '': self.alternateScenario.clear() self.alternateScenario.setEnabled(False) else: if len(self.alternateScenario) == 0: self.alternateScenario.setEnabled(True) self.alternateScenario.clear() self.__load_alternate_scenario_combobox() def __load_operators(self): """ @summary: Loads operators combo-box """ items = ["", "-", "/"] self.operators.addItems(items) def __reload_scenarios(self): """ @summary: Reloads scenarios """ self.scenarios_model = ScenariosModel(self) self.scenarios.setModel(self.scenarios_model) self.scenarios.setExpanded( self.scenarios_model.indexFromItem(self.scenarios_model.root_item), True) def __load_zone_lists(self): """ @summary: Loads zones lists """ items = self.project.map_data.get_matrix_zones() if items is not None: self.originList.addItem("All") self.originList.addItems(items) self.destinationList.addItem("All") self.destinationList.addItems(items) def __load_categories(self): """ @summary: Loads categories list """ items = self.project.map_data.get_matrix_categories() if items is not None: self.categories.addItem("All") self.categories.addItems(items) def __load_centroids(self): """ @summary: Loads centroids layer """ if not self.project.centroids_file_path is None: self.project.load_zones_centroids_data() else: self.__create_centroids_file() def __create_centroids_file(self): """ @summary: Creates centroids file """ self.project.load_zones_centroids() def create_layer(self): """ @summary: Creates matrix layer """ validationResult, scenariosExpression, matrixExpression, matrixExpressionText = self.__validate_data( ) if validationResult: self.progressBar.show() self.progressBar.setValue(20) method = self.method.currentText() if method == "Size": color = self.buttonColor.color() color = color.rgb() elif method == "Color": color = self.buttonColorRamp.colorRamp() color = color.properties() originZones = [] destinationZones = [] allOrigins = next((item for item in self.originList.selectedItems() if item.text() == 'All'), None) allDestinations = next( (item for item in self.destinationList.selectedItems() if item.text() == 'All'), None) if allOrigins is None: for item in self.originList.selectedItems(): originZones.append(item.text()) else: for index in range(self.originList.count()): if self.originList.item(index).text() != 'All': originZones.append(self.originList.item(index).text()) if allDestinations is None: for item in self.destinationList.selectedItems(): destinationZones.append(item.text()) else: for index in range(self.destinationList.count()): if self.destinationList.item(index).text() != 'All': destinationZones.append( self.destinationList.item(index).text()) method = method.strip() if not self.layerId: self.project.addMatrixLayer(self.progressBar, self.layerName.text(), scenariosExpression, originZones, destinationZones, matrixExpression, matrixExpressionText, method, color) else: self.project.editMatrixLayer(self.progressBar, self.layerName.text(), scenariosExpression, originZones, destinationZones, matrixExpression, matrixExpressionText, method, color, self.layerId) self.accept() else: #QMessageBox.critical(None, "New Layer", "New layer was not created.") print("New matrix layer was not created.") def category_selected(self, item): """ @summary: Detects when an item in the list is double clicked @param item: Item selected @type item: QListWidget item """ textToAdd = '' if item.text() == 'All': for index in range(1, self.categories.count()): textToAdd = self.categories.item( index).text() if textToAdd.strip( ) == '' else textToAdd + ' + ' + self.categories.item( index).text() else: textToAdd = item.text() if self.expression.text().strip() == '': self.expression.setText(self.expression.text() + textToAdd) else: self.expression.setText(self.expression.text() + " + " + textToAdd) def __validate_matrix_scenario(self, scenario): """ @summary: Validates the format of the file @param scenario: Scenario Id @type scenario: String """ if len(self.project.map_data.trip_matrices) > 0: for trip in self.project.map_data.trip_matrices: if trip.Id == scenario: if len(trip.tripMatrix.dtype) != 7: messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Matrix Scenario", "Scenario " + scenario + ", has an incorrect format.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Scenario {0}, has an incorrect format.").format( scenario) return False else: return True else: messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Matrix Scenario", "There are not scenarios information.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Matrix Scenario", "There are not scenarios information.") return False def __validate_data(self): """ @summary: Fields validation @return: Validation result, matrixExpressionResult and sectorsExpression """ scenariosExpression = [] if self.layerName.text().strip() == '': messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Layer Name", "Please write Layer Name.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Please write Layer Name.") return False, None, None, None if self.expression.text().strip() == '': messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Expression", "Please write an expression to be evaluated.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Please write an expression to be evaluated.") return False, None, None, None projectPath = self.project.shape[0:max(self.project.shape.rfind('\\'), self.project.shape.rfind('/'))] if len(self.base_scenario) == 0: messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Base Scenario", "There are no Base Scenarios loaded.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("There are no Base Scenarios loaded.") return False, None, None, None else: if self.project.load_map_trip_structure( projectPath, self.baseScenario.currentText()): if self.__validate_matrix_scenario( self.baseScenario.currentText()) == False: return False, None, None scenariosExpression.append(str( self.baseScenario.currentText())) else: messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Base Scenario", "Selected Base Scenario has no information.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Selected Base Scenario has no information.") return False, None, None, None # Validations for alternate scenario if self.operators.currentText() != '': scenariosExpression.append(str(self.operators.currentText())) if self.alternateScenario.currentText() == '': messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Alternate Scenario", "Please select an Alternate Scenario.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Please select an Alternate Scenario.") return False, None, None, None else: if self.project.load_map_trip_structure( projectPath, self.alternateScenario.currentText()): if self.__validate_matrix_scenario( self.alternateScenario.currentText()) == False: return False, None, None, None scenariosExpression.append( str(self.alternateScenario.currentText())) else: messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Alternate Scenario", "Selected Alternate Scenario has no information.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Selected Alternate Scenario has no information.") return False, None, None, None originSelectedCounter = len(self.originList.selectedItems()) destinationSelectedCounter = len(self.destinationList.selectedItems()) if originSelectedCounter == 0: messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Origin Zones", "Please select at least one origin zone.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Please select at least one origin zone.") return False, None, None, None if destinationSelectedCounter == 0: messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Destination Zones", "Please select at least one destination zone.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Please select at least one destination zone.") return False, None, None, None if originSelectedCounter == 1 and destinationSelectedCounter == 1: if self.originList.selectedItems()[0].text( ) == self.destinationList.selectedItems()[0].text(): if self.originList.selectedItems()[0].text() != "All": messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Zones", "You must select different origin and destination.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("You must select different origin and destination.") return False, None, None, None scenariosExpressionResult, scenariosExpressionStack = ExpressionData.validate_scenarios_expression( scenariosExpression) if scenariosExpressionResult: matrixExpressionResult, matrixExpressionList = ExpressionData.validate_sectors_expression( self.expression.text().strip()) if scenariosExpressionStack.tp > 1 and len(matrixExpressionList) > 1: messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Expression", "Expression with conditionals only applies for one scenario.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print( "Expression with conditionals only applies for one scenario.") return False, None, None, None if self.method.currentText( ) == 'Color' and self.buttonColorRamp.isNull(): messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Color Ramp", "Color Ramp is required.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Color Ramp is NULL.") return False, None, None, None elif self.method.currentText() == 'Size' and self.buttonColor.isNull(): messagebox = QTranusMessageBox.set_new_message_box( QtWidgets.QMessageBox.Warning, "Color", "Color is required.", ":/plugins/QTranus/icon.png", self, buttons=QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Color is NULL.") return False, None, None, None return scenariosExpressionResult and matrixExpressionResult, scenariosExpressionStack, matrixExpressionList, self.expression.text( )
class QadWindowColorDialog(QDialog, QObject, qad_windowcolor_ui.Ui_WindowColor_Dialog): def __init__(self, plugIn, parent, contextEnum=QadColorContextEnum.NONE, elementEnum=QadColorElementEnum.NONE): self.plugIn = plugIn self.iface = self.plugIn.iface.mainWindow() QDialog.__init__(self, parent) self.tempQadVariables = QadVariablesClass() QadVariables.copyTo(self.tempQadVariables) self.currentVarName = "" self.currentContext = contextEnum self.currentElement = elementEnum self.setupUi(self) # Inizializzazione dei colori self.init_colors() if contextEnum != QadColorContextEnum.NONE: # contesti index = self.listView_Context.model().index( 0, 0) # seleziono il primo elemento della lista context = self.contextList[ contextEnum] # context = (<contextEnum>, (<contextDescr>, <elementDict>)) contextDescr = context[0] items = self.listView_Context.model().findItems(contextDescr) if len(items) > 0: item = items[0] if item is not None: index = self.listView_Context.model().indexFromItem(item) self.listView_Context.selectionModel().setCurrentIndex( index, QItemSelectionModel.SelectCurrent) if elementEnum != QadColorElementEnum.NONE: # elementi elementDict = context[1] element = elementDict[ elementEnum] # element = (<elementEnum>, (<elementDescr>, <sys var name>)) elementDescr = element[0] items = self.listView_Element.model().findItems( elementDescr) if len(items) > 0: item = items[0] if item is not None: index = self.listView_Element.model( ).indexFromItem(item) self.listView_Element.selectionModel( ).setCurrentIndex( index, QItemSelectionModel.SelectCurrent) #============================================================================ # setupUi #============================================================================ def setupUi(self, Dialog): qad_windowcolor_ui.Ui_WindowColor_Dialog.setupUi(self, self) # aggiungo il bottone di qgis QgsColorButton chiamato buttonColor # che eredita la posizione di Button_ColorDummy (che viene nascosto) self.Button_ColorDummy.setHidden(True) self.buttonColor = QgsColorButton(self.Button_ColorDummy.parent()) self.buttonColor.setGeometry(self.Button_ColorDummy.geometry()) self.buttonColor.setObjectName("buttonColor") self.buttonColor.colorChanged.connect(self.colorChanged) # aggiungo il QWidget chiamato QadPreview # che eredita la posizione di widget_Preview (che viene nascosto) self.widget_Preview.setHidden(True) self.preview = QadPreview(self.plugIn, self.widget_Preview.parent(), self.tempQadVariables, self.currentContext) self.preview.setGeometry(self.widget_Preview.geometry()) self.preview.setObjectName("preview") #============================================================================ # init_context_list #============================================================================ def init_context_list(self): self.contextList = dict() # description, element dictionary contextDescr = QadMsg.translate("WindowColor_Dialog", "Model Space") # x lupdate self.contextList[QadColorContextEnum.MODEL_SPACE_2D] = [ contextDescr, self.get_MODEL_SPACE_2D_element_dict() ] contextDescr = QadMsg.translate("WindowColor_Dialog", "Command line") # x lupdate self.contextList[QadColorContextEnum.COMMAND_LINE] = [ contextDescr, self.get_COMMAND_LINE_element_dict() ] #============================================================================ # get_MODEL_SPACE_2D_element_dict #============================================================================ def get_MODEL_SPACE_2D_element_dict(self): elementList = dict() # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Crosshairs") # x lupdate elementVarName = QadMsg.translate("Environment variables", "CURSORCOLOR") # x lupdate elementList[QadColorElementEnum.CROSSHAIRS] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Pickbox") # x lupdate elementVarName = QadMsg.translate("Environment variables", "PICKBOXCOLOR") # x lupdate elementList[QadColorElementEnum.PICKBOX] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Autotreck vector") # x lupdate elementVarName = QadMsg.translate( "Environment variables", "AUTOTRECKINGVECTORCOLOR") # x lupdate elementList[QadColorElementEnum.AUTOTRECK_VECTOR] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Autosnap marker") # x lupdate elementVarName = QadMsg.translate("Environment variables", "AUTOSNAPCOLOR") # x lupdate elementList[QadColorElementEnum.AUTOSNAP_MARKER] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Dynamic dimension lines") # x lupdate elementVarName = QadMsg.translate( "Environment variables", "DYNTRECKINGVECTORCOLOR") # x lupdate elementList[QadColorElementEnum.DI_AUTOTRECK_VECTOR] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Drafting tool tip") # x lupdate elementVarName = QadMsg.translate("Environment variables", "DYNEDITFORECOLOR") # x lupdate elementList[QadColorElementEnum.DI_COMMAND_DESCR] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate( "WindowColor_Dialog", "Drafting tool tip contour") # x lupdate elementVarName = QadMsg.translate("Environment variables", "DYNEDITBORDERCOLOR") # x lupdate elementList[QadColorElementEnum.DI_COMMAND_DESCR_BACKGROUND] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate( "WindowColor_Dialog", "Drafting tool tip background") # x lupdate elementVarName = QadMsg.translate("Environment variables", "DYNEDITBACKCOLOR") # x lupdate elementList[QadColorElementEnum.DI_COMMAND_DESCR_BORDER] = [ elementDescr, elementVarName ] return elementList #============================================================================ # get_COMMAND_LINE_element_dict #============================================================================ def get_COMMAND_LINE_element_dict(self): elementList = dict() # description, system variable elementDescr = QadMsg.translate( "WindowColor_Dialog", "Command history background") # x lupdate elementVarName = QadMsg.translate("Environment variables", "CMDHISTORYBACKCOLOR") # x lupdate elementList[QadColorElementEnum.COMMAND_HISTORY_BACKGROUND] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Command history text") # x lupdate elementVarName = QadMsg.translate("Environment variables", "CMDHISTORYFORECOLOR") # x lupdate elementList[QadColorElementEnum.COMMAND_HISTORY_TEXT] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate( "WindowColor_Dialog", "Active prompt background") # x lupdate elementVarName = QadMsg.translate("Environment variables", "CMDLINEBACKCOLOR") # x lupdate elementList[QadColorElementEnum.PROMPT_BACKGROUND] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Active prompt text") # x lupdate elementVarName = QadMsg.translate("Environment variables", "CMDLINEFORECOLOR") # x lupdate elementList[QadColorElementEnum.PROMPT_TEXT] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate("WindowColor_Dialog", "Command option keyword") # x lupdate elementVarName = QadMsg.translate("Environment variables", "CMDLINEOPTCOLOR") # x lupdate elementList[QadColorElementEnum.COMMAND_OPTION_KEYWORD] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate( "WindowColor_Dialog", "Command option keyword background") # x lupdate elementVarName = QadMsg.translate("Environment variables", "CMDLINEOPTBACKCOLOR") # x lupdate elementList[QadColorElementEnum.COMMAND_OPTION_BACKGROUND] = [ elementDescr, elementVarName ] # description, system variable elementDescr = QadMsg.translate( "WindowColor_Dialog", "Command option highlighted") # x lupdate elementVarName = QadMsg.translate( "Environment variables", "CMDLINEOPTHIGHLIGHTEDCOLOR") # x lupdate elementList[QadColorElementEnum.COMMAND_OPTION_HIGHLIGHTED] = [ elementDescr, elementVarName ] return elementList #============================================================================ # init_colors #============================================================================ def init_colors(self): self.init_context_list() # Inizializzazione della lista dei contesti model = QStandardItemModel(self.listView_Context) contexts = self.contextList.items() # lista dei contesti for context in contexts: # context = (<contextEnum>, (<contextDescr>, <elementDict>)) contextDescr = context[1][0] # Create an item with a caption item = QStandardItem(contextDescr) item.setData(context) model.appendRow(item) self.listView_Context.setModel(model) # collego l'evento "cambio di selezione" alla funzione self.contextChanged self.listView_Context.selectionModel().selectionChanged.connect( self.contextChanged) #============================================================================ # contextChanged #============================================================================ def contextChanged(self, current, previous): # leggo ciò che selezionato index = current.indexes()[0] item = self.listView_Context.model().itemFromIndex(index) context = item.data( ) # context = (<contextEnum>, (<contextDescr>, <elementDict>)) self.currentContext = context[0] elementDict = context[1][1] self.preview.refreshColors( self.currentContext, self.tempQadVariables) # forzo il disegno del preview self.currentVarName = "" # Inizializzazione della lista dei contesti model = QStandardItemModel(self.listView_Element) elements = elementDict.items() # lista degli elementi for element in elements: # element = (<elementEnum>, (<elementDescr>, <sys var name>)) elementDescr = element[1][0] # Create an item with a caption item = QStandardItem(elementDescr) item.setData(element) model.appendRow(item) self.listView_Element.setModel(model) # collego l'evento "cambio di selezione" alla funzione self.elementChanged self.listView_Element.selectionModel().selectionChanged.connect( self.elementChanged) #============================================================================ # elementChanged #============================================================================ def elementChanged(self, current, previous): # leggo ciò che selezionato index = current.indexes()[0] item = self.listView_Element.model().itemFromIndex(index) element = item.data( ) # element = (<elementEnum>, (<elementDescr>, <sys var name>)) self.currentElement = element[0] self.currentVarName = element[1][1] self.buttonColor.setColor( QColor(self.tempQadVariables.get(self.currentVarName))) #============================================================================ # colorChanged #============================================================================ def colorChanged(self, value): self.tempQadVariables.set(self.currentVarName, self.buttonColor.color().name()) self.preview.refreshColors( self.currentContext, self.tempQadVariables) # forzo il disegno del preview #============================================================================ # restoreVarValueElement #============================================================================ def restoreVarValueElement(self, varName): variable = QadVariables.getVariable(varName) if variable is None: return False self.tempQadVariables.set(varName, variable.default) return True #============================================================================ # restoreContext #============================================================================ def restoreContext(self, context): context = self.contextList[ context] # context = (<contextEnum>, (<contextDescr>, <elementDict>)) elementDict = context[1] elements = elementDict.items() # lista degli elementi for element in elements: # element = (<elementEnum>, (<elementDescr>, <sys var name>)) varName = element[1][1] self.restoreVarValueElement(varName) #============================================================================ # Button_RestoreCurrElement_clicked #============================================================================ def Button_RestoreCurrElement_clicked(self): if self.restoreVarValueElement(self.currentVarName): self.preview.refreshColors( self.currentContext, self.tempQadVariables) # forzo il disegno del preview self.buttonColor.setColor( QColor(self.tempQadVariables.get(self.currentVarName))) #============================================================================ # Button_RestoreCurrContext_clicked #============================================================================ def Button_RestoreCurrContext_clicked(self): self.restoreContext(self.currentContext) self.preview.refreshColors( self.currentContext, self.tempQadVariables) # forzo il disegno del preview if self.currentVarName != "": self.buttonColor.setColor( QColor(self.tempQadVariables.get(self.currentVarName))) #============================================================================ # Button_RestoreAllContext_clicked #============================================================================ def Button_RestoreAllContext_clicked(self): contexts = self.contextList.keys() # lista dei contesti for context in contexts: self.restoreContext(context) self.preview.refreshColors( self.currentContext, self.tempQadVariables) # forzo il disegno del preview if self.currentVarName != "": self.buttonColor.setColor( QColor(self.tempQadVariables.get(self.currentVarName))) #============================================================================ # getSysVariableList #============================================================================ def getSysVariableList(self): # ritorna una lista di variabili di sistema dei colori gestiti da questa finestra variables = [] contexts = self.contextList.items() # lista dei contesti for context in contexts: # context = (<contextEnum>, (<contextDescr>, <elementDict>)) elementDict = context[1][1] elements = elementDict.items() # lista degli elementi for element in elements: # element = (<elementEnum>, (<elementDescr>, <sys var name>)) varName = element[1][1] varValue = self.tempQadVariables.get(varName) variables.append( QadVariable(varName, varValue, QadVariableTypeEnum.COLOR)) return variables def Button_ApplyClose_Pressed(self): # copio i valori dei colori in QadVariables e li salvo variables = self.getSysVariableList() for variable in variables: QadVariables.set(variable.name, variable.value) QadVariables.save() self.plugIn.TextWindow.refreshColors() QDialog.accept(self) def Button_Cancel_Pressed(self): QDialog.reject(self) def ButtonHELP_Pressed(self): qadShowPluginHelp(QadMsg.translate("Help", ""))
class QgsAnnotationWidget(QWidget): def __init__(self, parent, item): QWidget.__init__(self, parent) self.gridLayout_2 = QGridLayout(self) self.gridLayout_2.setObjectName(("gridLayout_2")) self.mMapPositionFixedCheckBox = QCheckBox(self) self.mMapPositionFixedCheckBox.setObjectName( ("mMapPositionFixedCheckBox")) self.gridLayout_2.addWidget(self.mMapPositionFixedCheckBox, 0, 0, 1, 1) self.gridLayout = QGridLayout() self.gridLayout.setObjectName(("gridLayout")) self.mFrameColorButton = QgsColorButton(self) self.mFrameColorButton.setText(("")) self.mFrameColorButton.setObjectName(("mFrameColorButton")) self.gridLayout.addWidget(self.mFrameColorButton, 3, 1, 1, 1) self.mFrameColorButton.colorChanged.connect( self.on_mFrameColorButton_colorChanged) self.mBackgroundColorLabel = QLabel(self) self.mBackgroundColorLabel.setObjectName(("mBackgroundColorLabel")) self.gridLayout.addWidget(self.mBackgroundColorLabel, 2, 0, 1, 1) self.mMapMarkerLabel = QLabel(self) self.mMapMarkerLabel.setObjectName(("mMapMarkerLabel")) self.gridLayout.addWidget(self.mMapMarkerLabel, 0, 0, 1, 1) self.mBackgroundColorButton = QgsColorButton(self) self.mBackgroundColorButton.setText(("")) self.mBackgroundColorButton.setObjectName(("mBackgroundColorButton")) self.gridLayout.addWidget(self.mBackgroundColorButton, 2, 1, 1, 1) self.mBackgroundColorButton.colorChanged.connect( self.on_mBackgroundColorButton_colorChanged) self.mMapMarkerButton = QPushButton(self) self.mMapMarkerButton.setText(("")) self.mMapMarkerButton.setObjectName(("mMapMarkerButton")) self.gridLayout.addWidget(self.mMapMarkerButton, 0, 1, 1, 1) self.mMapMarkerButton.clicked.connect(self.on_mMapMarkerButton_clicked) self.mFrameWidthLabel = QLabel(self) self.mFrameWidthLabel.setObjectName(("mFrameWidthLabel")) self.gridLayout.addWidget(self.mFrameWidthLabel, 1, 0, 1, 1) self.mFrameWidthSpinBox = QDoubleSpinBox(self) self.mFrameWidthSpinBox.setObjectName(("mFrameWidthSpinBox")) self.gridLayout.addWidget(self.mFrameWidthSpinBox, 1, 1, 1, 1) self.mFrameColorLabel = QLabel(self) self.mFrameColorLabel.setObjectName(("mFrameColorLabel")) self.gridLayout.addWidget(self.mFrameColorLabel, 3, 0, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1) self.mMapMarkerLabel.setBuddy(self.mMapMarkerButton) self.mFrameWidthLabel.setBuddy(self.mFrameWidthSpinBox) self.setWindowTitle("QgsAnnotationWidgetBase") self.mMapPositionFixedCheckBox.setText("Fixed map position") self.mBackgroundColorLabel.setText("Background color") self.mMapMarkerLabel.setText("Map marker") self.mFrameWidthLabel.setText("Frame width") self.mFrameColorLabel.setText("Frame color") self.setLayout(self.gridLayout_2) self.mItem = item if (self.mItem != None): self.blockAllSignals(True) if (self.mItem.mapPositionFixed()): self.mMapPositionFixedCheckBox.setCheckState(Qt.Checked) else: self.mMapPositionFixedCheckBox.setCheckState(Qt.Unchecked) self.mFrameWidthSpinBox.setValue(self.mItem.frameBorderWidth()) self.mFrameColorButton.setColor(self.mItem.frameColor()) self.mFrameColorButton.setColorDialogTitle("Select frame color") self.mFrameColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel) self.mBackgroundColorButton.setColor( self.mItem.frameBackgroundColor()) self.mBackgroundColorButton.setColorDialogTitle( "Select background color") self.mBackgroundColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel) self.symbol = self.mItem.markerSymbol() if (self.symbol != None): self.mMarkerSymbol = self.symbol.clone() self.updateCenterIcon() self.blockAllSignals(False) def apply(self): if (self.mItem != None): self.mItem.setMapPositionFixed( self.mMapPositionFixedCheckBox.checkState() == Qt.Checked) self.mItem.setFrameBorderWidth(self.mFrameWidthSpinBox.value()) self.mItem.setFrameColor(self.mFrameColorButton.color()) self.mItem.setFrameBackgroundColor( self.mBackgroundColorButton.color()) self.mItem.setMarkerSymbol(self.mMarkerSymbol) self.mMarkerSymbol = None #//item takes ownership self.mItem.update() def blockAllSignals(self, block): self.mMapPositionFixedCheckBox.blockSignals(block) self.mMapMarkerButton.blockSignals(block) self.mFrameWidthSpinBox.blockSignals(block) self.mFrameColorButton.blockSignals(block) def on_mMapMarkerButton_clicked(self): if (self.mMarkerSymbol == None): return markerSymbol = self.mMarkerSymbol.clone() dlg = QgsSymbolV2SelectorDialog(markerSymbol, QgsStyleV2.defaultStyle(), None, self) if (dlg.exec_() != QDialog.Rejected): self.mMarkerSymbol = markerSymbol self.updateCenterIcon() def on_mFrameColorButton_colorChanged(self, color): if (self.mItem == None): return self.mItem.setFrameColor(color) def updateCenterIcon(self): if (self.mMarkerSymbol == None): return icon = QgsSymbolLayerV2Utils.symbolPreviewIcon( self.mMarkerSymbol, self.mMapMarkerButton.iconSize()) self.mMapMarkerButton.setIcon(icon) def on_mBackgroundColorButton_colorChanged(self, color): if (self.mItem == None): return self.mItem.setFrameBackgroundColor(color)
class NetworkLayerDialog(QtWidgets.QDialog, FORM_CLASS): def __init__(self, parent = None, layerId=None): """ @summary: Class constructor @param parent: Class that contains project information @type parent: QTranusProject class """ super(NetworkLayerDialog, self).__init__(parent) self.setupUi(self) self.project = parent.project self.network = Network() self.level = None self.tempLayerName = '' self.tempExpression = '' self.layerId = layerId self.labelColor = QLabel("Color") self.buttonColorRamp = QgsColorRampButton(self, 'Color Ramp') self.buttonColorRamp.hide() self.buttonColor = QgsColorButton(self, 'Color') self.buttonColor.hide() #self.buttonColorRamp = QgsColorRampButton(self, 'Color Ramp') # Linking objects with controls self.help = self.findChild(QtWidgets.QPushButton, 'btn_help') self.layerName = self.findChild(QtWidgets.QLineEdit, 'layerName') self.expression = self.findChild(QtWidgets.QLineEdit, 'expression') self.baseScenario = self.findChild(QtWidgets.QComboBox, 'base_scenario') self.scenarioOperator = self.findChild(QtWidgets.QComboBox, name='cb_operator') self.alternateScenario = self.findChild(QtWidgets.QComboBox, name='cb_alternate_scenario') self.variablesList = self.findChild(QtWidgets.QComboBox, name='cb_variables') self.method = self.findChild(QtWidgets.QComboBox, name='cb_method') self.total = self.findChild(QtWidgets.QRadioButton, 'rbtn_total') self.operators = self.findChild(QtWidgets.QRadioButton, 'rbtn_operators') self.routes = self.findChild(QtWidgets.QRadioButton, 'rbtn_routes') self.list = self.findChild(QtWidgets.QListWidget, 'list') self.scenarios = self.findChild(QtWidgets.QTreeView, 'scenarios') self.buttonBox = self.findChild(QtWidgets.QDialogButtonBox, 'buttonBox') self.progressBar = self.findChild(QtWidgets.QProgressBar, 'progressBar') # Control Actions self.help.clicked.connect(self.open_help) self.layerName.keyPressEvent = self.keyPressEvent self.expression.keyPressEvent = self.expression_key_press_event self.buttonBox.accepted.connect(self.create_layer) self.scenarioOperator.currentIndexChanged[int].connect(self.scenario_operator_changed) self.baseScenario.currentIndexChanged[int].connect(self.scenario_changed) self.variablesList.currentIndexChanged[int].connect(self.variable_changed) self.method.currentIndexChanged[int].connect(self.method_changed) self.total.clicked.connect(self.total_checked) self.operators.clicked.connect(self.operator_checked) self.routes.clicked.connect(self.routes_checked) self.list.itemDoubleClicked.connect(self.list_item_selected) #self.color.clicked.connect(self.color_picker) # Controls settings self.alternateScenario.setEnabled(False) # Loads combo-box controls self.__load_scenario_operators() self.__load_scenarios_combobox() self.__load_variable_combobox() self.__reload_scenarios() if self.layerId: self.__load_default_data() def open_help(self): """ @summary: Opens QTranus users help """ filename = "file:///" + os.path.join(os.path.dirname(os.path.realpath(__file__)) + "/userHelp/", 'network.html') webbrowser.open_new_tab(filename) def keyPressEvent(self, event): """ @summary: Detects when a key is pressed @param event: Key press event @type event: Event object """ QtWidgets.QLineEdit.keyPressEvent(self.layerName, event) if not self.validate_string(event.text()): messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Layer Name", "Invalid character: " + event.text() + ".", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() if self.layerName.isUndoAvailable(): self.layerName.setText(self.tempLayerName) else: self.tempLayerName = self.layerName.text() def method_changed(self, event): if self.method.currentText() == "Color": self.labelColor.setText("Color Ramp") self.formLayout = self.findChild(QFormLayout, 'formLayout_4') self.formLayout.takeAt(10) self.buttonColor.hide() self.buttonColorRamp.show() self.buttonColorRamp.setShowGradientOnly(True) self.formLayout.addRow(self.labelColor, self.buttonColorRamp) elif self.method.currentText() == "Size": self.labelColor.setText("Color") self.formLayout = self.findChild(QFormLayout, 'formLayout_4') self.formLayout.takeAt(10) self.buttonColorRamp.hide() self.buttonColor.show() self.formLayout.addRow(self.labelColor, self.buttonColor) def expression_key_press_event(self, event): """ @summary: Detects when a key is pressed @param event: Key press event @type event: Event object """ QtWidgets.QLineEdit.keyPressEvent(self.expression, event) if not self.invalid_expression_characters(event.text()): messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Network Expression", "Invalid character: " + event.text() + ".", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() if self.expression.isUndoAvailable(): self.expression.setText(self.tempExpression) else: self.tempExpression = self.expression.text() def validate_string(self, input): """ @summary: Validates invalid characters @param input: Input string @type input: String object @return: Result of the evaluation """ pattern = re.compile('[\\\/\:\*\?\"\<\>\|]') if re.match(pattern, input) is None: return True else: return False def invalid_expression_characters(self, input): """ @summary: Validates invalid characters @param input: Input string @type input: String object @return: Result of the evaluation """ pattern = re.compile('[\\\/\:\*\-\<\>\|\=]') if re.match(pattern, input) is None: return True else: return False def __load_scenarios_combobox(self): """ @summary: Loads scenarios combo-box """ self.network.load_network_scenarios(self.project['tranus_folder']) items = self.network.get_sorted_scenarios() if items is not None: self.base_scenario.addItems(items) def __load_alternate_scenario_combobox(self): """ @summary: Loads alternate scenario combo-box """ baseScenario = self.baseScenario.currentText() items = self.network.get_sorted_scenarios() for item in items: if item != baseScenario: self.alternateScenario.addItem(item) def __load_variable_combobox(self): """ @summary: Loads data to variable combo-box control """ self.project.network_model.load_dictionaries() items = self.project.network_model.get_sorted_variables() if items is None: messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Variables", "There are no variables to load.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print ("There are no variables to load.") else: self.variablesList.addItems(items) def scenario_changed(self, newIndex): """ @summary: Detects when an scenario was changed """ if self.scenarioOperator.currentText() != '': self.alternateScenario.clear() self.__load_alternate_scenario_combobox() def variable_changed(self, newIndex): """ @summary: Detects when an scenario was changed """ if self.variablesList.currentText() != '': method = HP.method_x_varible(self.variablesList.currentText()) indexMethod = self.method.findText(method, Qt.MatchFixedString) self.method.setCurrentIndex(indexMethod) def scenario_operator_changed(self): """ @summary: Detects when an operator was changed """ currentOperator = self.scenarioOperator.currentText() if self.scenarioOperator.currentText() == '': self.alternateScenario.clear() self.alternateScenario.setEnabled(False) else: if len(self.alternateScenario) == 0: self.alternateScenario.setEnabled(True) self.alternateScenario.clear() self.__load_alternate_scenario_combobox() def __load_scenario_operators(self): """ @summary: Loads operators combo-box """ items = ["", "-"] self.scenarioOperator.addItems(items) def __reload_scenarios(self): """ @summary: Reloads scenarios """ self.scenarios_model = ScenariosModel(self) self.scenarios.setModel(self.scenarios_model) self.scenarios.setExpanded(self.scenarios_model.indexFromItem(self.scenarios_model.root_item), True) def total_checked(self): """ @summary: Functionality when user click total radio button """ self.list.clear() self.expression.clear() self.expression.setEnabled(False) self.level = Level.Total def operator_checked(self): """ @summary: Functionality when user click operator radio button """ if self.operators.isChecked(): self.list.clear() self.expression.clear() self.expression.setEnabled(True) self.network.load_operators(self.project['tranus_folder'], self.baseScenario.currentText()) self.level = Level.Operators operators = self.network.get_operators_dictionary() if operators is not None: self.list.addItem("All") for key, value in operators.items(): self.list.addItem(str(key) + ' - ' + value) def routes_checked(self): """ @summary: Functionality when user click routes radio button """ if self.routes.isChecked(): self.list.clear() self.expression.clear() self.expression.setEnabled(True) self.network.load_routes(self.project['tranus_folder'], self.baseScenario.currentText()) self.level = Level.Routes routes = self.network.get_routes_dictionary() if routes is not None: self.list.addItem("All") for key, value in sorted(routes.items()): self.list.addItem(str(key) + ' - ' + value) def list_item_selected(self, item): """ @summary: Selects item clicked from the list. @param item: Item selected @type item: String """ textToAdd = '' if item.text() == 'All': if self.level == Level.Operators: itemsDic = self.network.get_operators_dictionary() if self.level == Level.Routes: itemsDic = self.network.get_routes_dictionary() if itemsDic is not None: for value in itemsDic.values(): textToAdd = value if textToAdd.strip() == '' else textToAdd + ' + ' + value else: posStrFound = item.text().find(" - ") textToAdd = item.text() if posStrFound == -1 else item.text()[posStrFound + 3:] if self.expression.text().strip() == '': self.expression.setText(self.expression.text() + textToAdd) else: self.expression.setText(self.expression.text() + " + " + textToAdd) self.tempExpression = self.expression.text() def __validate_data(self): """ @summary: Fields validation @return: Validation result, matrixExpressionResult and sectorsExpression """ scenariosExpression = [] if self.layerName.text().strip() == '': messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Layer Name", "Please write Layer Name.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print ("Please write Layer Name.") return False, None, None, None if self.expression.text().strip() == '' and (self.level is not Level.Total):#self.operators.isChecked() or self.routes.isChecked()): messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Expression", "Please write an expression to be evaluated.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print ("Please write an expression to be evaluated.") return False, None, None, None # Base scenario if len(self.base_scenario) == 0: messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Base Scenario", "There are no Base Scenarios loaded.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print ("There are no Base Scenarios loaded.") return False, None, None, None else: if self.baseScenario.currentText().strip() != '': scenariosExpression.append(str(self.baseScenario.currentText())) else: messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Base Scenario", "Please select a Base Scenario.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Please select a Base Scenario.") return False, None, None, None # Validations for alternate scenario if self.scenarioOperator.currentText() != '': scenariosExpression.append(str(self.scenarioOperator.currentText())) if self.alternateScenario.currentText() == '': messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Alternate Scenario", "Please select an Alternate Scenario.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Please select an Alternate Scenario.") return False, None, None, None else: scenariosExpression.append(str(self.alternateScenario.currentText())) if self.variablesList.currentText() == '': messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Variable", "Please select a variable.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print ("Please write an expression to be evaluated.") return False, None, None, None scenariosExpressionResult, scenariosExpressionStack = ExpressionData.validate_scenarios_expression(scenariosExpression) if scenariosExpressionResult: if self.level == Level.Total: networkExpressionResult = True networkExpressionList = None else: networkExpressionResult, networkExpressionList = ExpressionData.validate_sectors_expression(self.expression.text().strip()) if self.level is not Level.Total: if scenariosExpressionStack.tp > 1 and len(networkExpressionList) > 1: messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Expression", "Expression with conditionals only applies for one scenario.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Expression with conditionals only applies for one scenario.") return False, None, None, None if self.method.currentText()=='Color' and self.buttonColorRamp.isNull(): messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Color Ramp", "Color Ramp is required.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Color Ramp is NULL.") return False, None, None, None elif self.method.currentText()=='Size' and self.buttonColor.isNull(): messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Color", "Color is required.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() print("Color is NULL.") return False, None, None, None return scenariosExpressionResult and networkExpressionResult, scenariosExpressionStack, networkExpressionList, self.expression.text() def create_layer(self): """ @summary: Method that creates new network layer. @return: Result of the process """ validationResult, scenariosExpression, networkExpression, expressionNetworkText = self.__validate_data() if validationResult: self.progressBar.show() self.progressBar.setValue(10) if self.method.currentText()=="Size": color = self.buttonColor.color() color = color.rgb() elif self.method.currentText()=="Color": color = self.buttonColorRamp.colorRamp() color = color.properties() # Set Custom Project Variable to save Project path projectPath = self.project.network_link_shape_path[0:max(self.project.network_link_shape_path.rfind('\\'), self.project.network_link_shape_path.rfind('/'))] tranus_dictionary = dict(project_qtranus_folder=projectPath, project_qtranus_network_shape=self.project.network_link_shape_path) self.project.custom_variables_dict.update(tranus_dictionary) QgsProject.instance().setCustomVariables(self.project.custom_variables_dict) if not self.layerId: result = self.network.addNetworkLayer(self.progressBar, self.layerName.text(), scenariosExpression, networkExpression, self.variablesList.currentText(), self.level, self.project['tranus_folder'], self.project.get_layers_group(), self.project.network_link_shape_path, self.method.currentText(), expressionNetworkText, color) else: result = self.network.editNetworkLayer(self.progressBar, self.layerName.text(), scenariosExpression, networkExpression, self.variablesList.currentText(), self.level, self.project['tranus_folder'], self.project.get_layers_group(), self.project.network_link_shape_path, self.method.currentText(), self.layerId, expressionNetworkText, color) if not result: messagebox = QTranusMessageBox.set_new_message_box(QtWidgets.QMessageBox.Warning, "Network", "Could not create network layer.", ":/plugins/QTranus/icon.png", self, buttons = QtWidgets.QMessageBox.Ok) messagebox.exec_() self.project['network_links_shape_file_path'] = '' self.project['network_links_shape_id'] = '' self.accept() else: print("New network layer was not created.") #print("Color Ramp {} ".format(self.buttonColorRamp.colorRampName())) return True # Load data to edit the zones layer def __load_default_data(self): projectPath = self.project.shape[0:max(self.project.shape.rfind('\\'), self.project.shape.rfind('/'))] # Get data from XML File with the parameters expression, field, name, scenario, fieldName, method, level, color = FileM.find_layer_data(projectPath, self.layerId) self.layerName.setText(name) if level == "1": self.total.click() self.rbtn_total.setChecked(True) elif level == "2": self.rbtn_operators.setChecked(True) self.operators.click() elif level == "3": self.rbtn_routes.setChecked(True) self.routes.click() self.expression.setText(expression) scenario = scenario.split(",") scenario[0] = scenario[0].replace("'", "").replace("[", "").replace("]", "") indexBaseScenario = self.base_scenario.findText(scenario[0], Qt.MatchFixedString) self.base_scenario.setCurrentIndex(indexBaseScenario) indexVariable = self.variablesList.findText(field, Qt.MatchFixedString) self.variablesList.setCurrentIndex(indexVariable) indexMethod = self.method.findText(method, Qt.MatchFixedString) self.method.setCurrentIndex(indexMethod) if method == 'Size': qcolor = QColor() qcolor.setRgb(int(color)) self.buttonColor.setColor(qcolor) if method == 'Color': color = literal_eval(color) arrColor1 = color['color1'].split(",") arrColor2 = color['color2'].split(",") arrColor1 = list(map(lambda x:int(x),arrColor1)) arrColor2 = list(map(lambda x:int(x),arrColor2)) qcolor1 = QColor(arrColor1[0], arrColor1[1], arrColor1[2]) qcolor2 = QColor(arrColor2[0], arrColor2[1], arrColor2[2]) qColorRamp = QgsGradientColorRamp() qColorRamp.setColor1(qcolor1) qColorRamp.setColor2(qcolor2) self.buttonColorRamp.setColorRamp(qColorRamp) if len(scenario) == 3: scenario[2] = scenario[2].replace("'", "").replace("]", "").strip() indexOperators = self.scenarioOperator.findText(scenario[2] , Qt.MatchFixedString) self.scenarioOperator.setCurrentIndex(indexOperators) scenario[1] = scenario[1].replace("'", "").strip() indexAlternateScenario = self.alternateScenario.findText(scenario[1], Qt.MatchFixedString) self.alternateScenario.setCurrentIndex(indexAlternateScenario)
class PresetRow(): def __init__(self, qgsfieldexpressionwidget=None, qgscolorbutton=None, qspinbox=None): self._qgsfieldexpressionwidget = qgsfieldexpressionwidget if qgsfieldexpressionwidget is None: self._qgsfieldexpressionwidget = QgsFieldExpressionWidget() self._qgscolorbutton = qgscolorbutton if qgscolorbutton is None: self._qgscolorbutton = QgsColorButton() self._qspinbox = qspinbox if qspinbox is None: self._qspinbox = QtGui.QSpinBox() self._last_feature = None def set_layer(self, layer_id): self._qgsfieldexpressionwidget.setLayer(layer_id) def __del__(self): self._qgsfieldexpressionwidget.deleteLater() self._qgsfieldexpressionwidget = None self._qgscolorbutton.deleteLater() self._qgscolorbutton = None self._qspinbox.deleteLater() self._qspinbox = None def __str__(self): return "{}-{}-{}".format(str(self._qgsfieldexpressionwidget), str(self._qgscolorbutton), str(self._qspinbox)) def __repr__(self): return self.__str__() def asLst(self): return self._qgscolorbutton, self._qgsfieldexpressionwidget, self._qspinbox @property def qgsfieldexp(self): return self._qgsfieldexpressionwidget @property def exp_txt(self): return self._qgsfieldexpressionwidget.currentText() @property def qgscolorbutton(self): return self._qgscolorbutton @property def qspinbox(self): return self._qspinbox @property def lvl(self): return self._qspinbox.value() def copy(self): field_expression_widget = QgsFieldExpressionWidget() field_expression_widget.setLayer( self._qgsfieldexpressionwidget.layer()) field_expression_widget.setField( self._qgsfieldexpressionwidget.currentText()) color_btn_widget = QgsColorButton() color_btn_widget.setColor(self._qgscolorbutton.color()) spinbox = QtGui.QSpinBox() spinbox.setValue(self._qspinbox.value()) return PresetRow(field_expression_widget, color_btn_widget, spinbox) #=========================================================================== # #=========================================================================== def dump(self): exp = self._qgsfieldexpressionwidget.currentText() #color=self._qgscolorbutton.color().name() color = self._qgscolorbutton.color().rgba() idx = self._qspinbox.value() res = {"exp": exp, "color": color, "idx": idx} return json.dumps(res) #======================================================================= # #======================================================================= def load(self, str_dump): res = json.loads(str_dump) self._qgsfieldexpressionwidget.setField(res["exp"]) #self._qgscolorbutton.color().setNamedColor(res["color"]) qcolor = self._qgscolorbutton.color() qcolor.setRgba(res["color"]) self._qgscolorbutton.setColor(qcolor) self._qspinbox.setValue(res["idx"]) @property def exp(self): return QgsExpression(self._qgsfieldexpressionwidget.asExpression()) @property def qcolor(self): return self._qgscolorbutton.color() @property def color_rgba(self): return self._qgscolorbutton.color().rgba() @property def color_hex(self): return self._qgscolorbutton.color().name() def setFeature(self, feature): self._last_feature = feature def execute(self, feature=None): if feature is not None: self.setFeature(feature) if self._last_feature is None: return None else: return self.exp.evaluate(self._last_feature)
class SettingsWidget(QtWidgets.QDialog, FORM_CLASS): updated = QtCore.pyqtSignal(Settings.Snapshot) def __init__(self, parent=None): super().__init__(parent) self.setupUi(self) self._background_color = QgsColorButton() self.mBackgroundLayout.addWidget(self._background_color) self._labels_color = QgsColorButton() self.mAxesLabelsLayout.addWidget(self._labels_color) self._axes_color = QgsColorButton() self.mAxesLayout.addWidget(self._axes_color) self._single_color = QgsColorButton() self.mSingleColorLayout.addWidget(self._single_color) self.mButtons.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect( self.apply) self.mButtons.button( QtWidgets.QDialogButtonBox.Cancel).clicked.connect(self.cancel) self.read_settings() def read_settings(self): setting = Settings.Chart.BackgroundColor color = Settings.get(setting, QtGui.QColor("white")) self._background_color.setColor(QtGui.QColor(color)) setting = Settings.Chart.AxisColor color = Settings.get(setting, QtGui.QColor("grey")) self._axes_color.setColor(QtGui.QColor(color)) setting = Settings.Chart.LabelsColor color = Settings.get(setting, QtGui.QColor("white")) self._labels_color.setColor(QtGui.QColor(color)) setting = Settings.Profile.Budget value = Settings.get(setting, 100000, int) self.budget.setValue(value) setting = Settings.Profile.SingleColor color = Settings.get(setting, QtGui.QColor("blue")) self._single_color.setColor(QtGui.QColor(color)) def cancel(self): snapshot = Settings.Snapshot() self.updated.emit(snapshot) self.read_settings() def apply(self): snapshot = Settings.Snapshot() snapshot.background_color = self._background_color.color().name() snapshot.axes_color = self._axes_color.color().name() snapshot.labels_color = self._labels_color.color().name() snapshot.opengl = self.opengl.isChecked() snapshot.budget = self.budget.value() snapshot.single_color = self._single_color.color().name() self.updated.emit(snapshot) def accept(self): self.store() self.apply() self.close() def store(self): color = self._background_color.color().name() setting = Settings.Chart.BackgroundColor Settings.set(setting, color) color = self._axes_color.color().name() setting = Settings.Chart.AxisColor Settings.set(setting, color) color = self._labels_color.color().name() setting = Settings.Chart.LabelsColor Settings.set(setting, color) value = self.opengl.isChecked() setting = Settings.Chart.OpenGL Settings.set(setting, value) value = self.budget.value() setting = Settings.Profile.Budget Settings.set(setting, value) color = self._single_color.color().name() setting = Settings.Profile.SingleColor Settings.set(setting, color)
class ModelerParameterDefinitionDialog(QDialog): @staticmethod def use_legacy_dialog(param=None, paramType=None): if paramType in (parameters.PARAMETER_TABLE_FIELD, parameters.PARAMETER_BAND, parameters.PARAMETER_VECTOR, parameters.PARAMETER_TABLE, parameters.PARAMETER_MULTIPLE, parameters.PARAMETER_NUMBER, parameters.PARAMETER_DISTANCE, parameters.PARAMETER_SCALE, parameters.PARAMETER_MAP_LAYER): return True elif isinstance( param, (QgsProcessingParameterField, QgsProcessingParameterBand, QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer, QgsProcessingParameterMultipleLayers, QgsProcessingParameterNumber, QgsProcessingParameterDistance, QgsProcessingParameterScale, QgsProcessingParameterMapLayer, QgsProcessingDestinationParameter)): return True # yay, use new API! return False def __init__(self, alg, paramType=None, param=None): self.alg = alg self.paramType = paramType self.param = param QDialog.__init__(self) self.setModal(True) self.setupUi() settings = QgsSettings() self.restoreGeometry( settings.value( "/Processing/modelParametersDefinitionDialogGeometry", QByteArray())) def closeEvent(self, event): settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) super(ModelerParameterDefinitionDialog, self).closeEvent(event) def switchToCommentTab(self): self.tab.setCurrentIndex(1) self.commentEdit.setFocus() self.commentEdit.selectAll() def setupUi(self): type_metadata = QgsApplication.processingRegistry().parameterType( self.param.type() if self.param else self.paramType) self.setWindowTitle( self.tr('{} Parameter Definition').format(type_metadata.name())) self.mainLayout = QVBoxLayout() self.tab = QTabWidget() self.mainLayout.addWidget(self.tab) self.setMinimumWidth(300) self.verticalLayout = QVBoxLayout() self.label = QLabel(self.tr('Parameter name')) self.verticalLayout.addWidget(self.label) self.nameTextBox = QLineEdit() self.verticalLayout.addWidget(self.nameTextBox) if isinstance(self.param, QgsProcessingParameterDefinition): self.nameTextBox.setText(self.param.description()) if self.paramType == parameters.PARAMETER_TABLE_FIELD or \ isinstance(self.param, QgsProcessingParameterField): self.verticalLayout.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in list(self.alg.parameterComponents().values()): definition = self.alg.parameterDefinition( param.parameterName()) if isinstance(definition, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer)): self.parentCombo.addItem(definition.description(), definition.name()) if self.param is not None: if self.param.parentLayerParameterName( ) == definition.name(): self.parentCombo.setCurrentIndex(idx) idx += 1 self.verticalLayout.addWidget(self.parentCombo) # add the datatype selector self.verticalLayout.addWidget(QLabel(self.tr('Allowed data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any'), -1) self.datatypeCombo.addItem(self.tr('Number'), 0) self.datatypeCombo.addItem(self.tr('String'), 1) self.datatypeCombo.addItem(self.tr('Date/time'), 2) self.verticalLayout.addWidget(self.datatypeCombo) if self.param is not None and self.param.dataType() is not None: # QComboBoxes indexes start at 0, # self.param.datatype start with -1 that is why I need to do +1 datatypeIndex = self.param.dataType() + 1 self.datatypeCombo.setCurrentIndex(datatypeIndex) self.multipleCheck = QCheckBox() self.multipleCheck.setText(self.tr('Accept multiple fields')) self.multipleCheck.setChecked(False) if self.param is not None: self.multipleCheck.setChecked(self.param.allowMultiple()) self.verticalLayout.addWidget(self.multipleCheck) self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setToolTip( self. tr('Default field name, or ; separated list of field names for multiple field parameters' )) if self.param is not None: default = self.param.defaultValue() if default is not None: self.defaultTextBox.setText(str(default)) self.verticalLayout.addWidget(self.defaultTextBox) elif self.paramType == parameters.PARAMETER_BAND or \ isinstance(self.param, QgsProcessingParameterBand): self.verticalLayout.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in list(self.alg.parameterComponents().values()): definition = self.alg.parameterDefinition( param.parameterName()) if isinstance(definition, (QgsProcessingParameterRasterLayer)): self.parentCombo.addItem(definition.description(), definition.name()) if self.param is not None: if self.param.parentLayerParameterName( ) == definition.name(): self.parentCombo.setCurrentIndex(idx) idx += 1 self.verticalLayout.addWidget(self.parentCombo) elif (self.paramType in (parameters.PARAMETER_VECTOR, parameters.PARAMETER_TABLE) or isinstance(self.param, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer))): self.verticalLayout.addWidget(QLabel(self.tr('Geometry type'))) self.shapetypeCombo = QComboBox() self.shapetypeCombo.addItem(self.tr('Geometry Not Required'), QgsProcessing.TypeVector) self.shapetypeCombo.addItem(self.tr('Point'), QgsProcessing.TypeVectorPoint) self.shapetypeCombo.addItem(self.tr('Line'), QgsProcessing.TypeVectorLine) self.shapetypeCombo.addItem(self.tr('Polygon'), QgsProcessing.TypeVectorPolygon) self.shapetypeCombo.addItem(self.tr('Any Geometry Type'), QgsProcessing.TypeVectorAnyGeometry) if self.param is not None: self.shapetypeCombo.setCurrentIndex( self.shapetypeCombo.findData(self.param.dataTypes()[0])) self.verticalLayout.addWidget(self.shapetypeCombo) elif (self.paramType == parameters.PARAMETER_MULTIPLE or isinstance(self.param, QgsProcessingParameterMultipleLayers)): self.verticalLayout.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any Map Layer'), QgsProcessing.TypeMapLayer) self.datatypeCombo.addItem( self.tr('Vector (No Geometry Required)'), QgsProcessing.TypeVector) self.datatypeCombo.addItem(self.tr('Vector (Point)'), QgsProcessing.TypeVectorPoint) self.datatypeCombo.addItem(self.tr('Vector (Line)'), QgsProcessing.TypeVectorLine) self.datatypeCombo.addItem(self.tr('Vector (Polygon)'), QgsProcessing.TypeVectorPolygon) self.datatypeCombo.addItem(self.tr('Vector (Any Geometry Type)'), QgsProcessing.TypeVectorAnyGeometry) self.datatypeCombo.addItem(self.tr('Raster'), QgsProcessing.TypeRaster) self.datatypeCombo.addItem(self.tr('File'), QgsProcessing.TypeFile) if self.param is not None: self.datatypeCombo.setCurrentIndex( self.datatypeCombo.findData(self.param.layerType())) self.verticalLayout.addWidget(self.datatypeCombo) elif (self.paramType == parameters.PARAMETER_MAP_LAYER or isinstance(self.param, QgsProcessingParameterMapLayer)): self.verticalLayout.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any Map Layer'), QgsProcessing.TypeMapLayer) self.datatypeCombo.addItem(self.tr('Vector (Point)'), QgsProcessing.TypeVectorPoint) self.datatypeCombo.addItem(self.tr('Vector (Line)'), QgsProcessing.TypeVectorLine) self.datatypeCombo.addItem(self.tr('Vector (Polygon)'), QgsProcessing.TypeVectorPolygon) self.datatypeCombo.addItem(self.tr('Vector (Any Geometry Type)'), QgsProcessing.TypeVectorAnyGeometry) self.datatypeCombo.addItem(self.tr('Raster'), QgsProcessing.TypeRaster) self.datatypeCombo.addItem(self.tr('Mesh'), QgsProcessing.TypeMesh) if self.param is not None: self.datatypeCombo.setCurrentIndex( self.datatypeCombo.findData(self.param.dataTypes()[0])) self.verticalLayout.addWidget(self.datatypeCombo) elif (self.paramType in (parameters.PARAMETER_NUMBER, parameters.PARAMETER_DISTANCE, parameters.PARAMETER_SCALE) or isinstance(self.param, (QgsProcessingParameterNumber, QgsProcessingParameterDistance, QgsProcessingParameterScale))): if (self.paramType == parameters.PARAMETER_DISTANCE or isinstance(self.param, QgsProcessingParameterDistance)): self.verticalLayout.addWidget(QLabel(self.tr('Linked input'))) self.parentCombo = QComboBox() self.parentCombo.addItem('', '') idx = 1 for param in list(self.alg.parameterComponents().values()): definition = self.alg.parameterDefinition( param.parameterName()) if isinstance(definition, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer, QgsProcessingParameterMapLayer, QgsProcessingParameterCrs)): self.parentCombo.addItem(definition.description(), definition.name()) if self.param is not None: if self.param.parentParameterName( ) == definition.name(): self.parentCombo.setCurrentIndex(idx) idx += 1 self.verticalLayout.addWidget(self.parentCombo) elif (self.paramType != parameters.PARAMETER_SCALE and not isinstance(self.param, QgsProcessingParameterScale)): self.verticalLayout.addWidget(QLabel(self.tr('Number type'))) self.type_combo = QComboBox() self.type_combo.addItem(self.tr('Float'), QgsProcessingParameterNumber.Double) self.type_combo.addItem(self.tr('Integer'), QgsProcessingParameterNumber.Integer) if self.param: self.type_combo.setCurrentIndex( self.type_combo.findData(self.param.dataType())) self.verticalLayout.addWidget(self.type_combo) if (self.paramType != parameters.PARAMETER_SCALE and not isinstance(self.param, QgsProcessingParameterScale)): self.verticalLayout.addWidget(QLabel(self.tr('Min value'))) self.minTextBox = QLineEdit() self.verticalLayout.addWidget(self.minTextBox) self.verticalLayout.addWidget(QLabel(self.tr('Max value'))) self.maxTextBox = QLineEdit() self.verticalLayout.addWidget(self.maxTextBox) if self.param is not None: self.minTextBox.setText(str(self.param.minimum())) self.maxTextBox.setText(str(self.param.maximum())) self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setText(self.tr('0')) if self.param is not None: default = self.param.defaultValue() if self.param.dataType( ) == QgsProcessingParameterNumber.Integer: default = int(math.floor(float(default))) if default: self.defaultTextBox.setText(str(default)) self.verticalLayout.addWidget(self.defaultTextBox) elif isinstance(self.param, QgsProcessingDestinationParameter): self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultWidget = QgsProcessingLayerOutputDestinationWidget( self.param, defaultSelection=True) self.verticalLayout.addWidget(self.defaultWidget) self.verticalLayout.addSpacing(20) self.requiredCheck = QCheckBox() self.requiredCheck.setText(self.tr('Mandatory')) self.requiredCheck.setChecked(True) if self.param is not None: self.requiredCheck.setChecked( not self.param.flags() & QgsProcessingParameterDefinition.FlagOptional) self.verticalLayout.addWidget(self.requiredCheck) self.advancedCheck = QCheckBox() self.advancedCheck.setText(self.tr('Advanced')) self.advancedCheck.setChecked(False) if self.param is not None: self.advancedCheck.setChecked( self.param.flags() & QgsProcessingParameterDefinition.FlagAdvanced) self.verticalLayout.addWidget(self.advancedCheck) # If child algorithm output is mandatory, disable checkbox if isinstance(self.param, QgsProcessingDestinationParameter): provider_name, child_name, output_name = self.param.name().split( ':') child = self.alg.childAlgorithms()['{}:{}'.format( provider_name, child_name)] model_output = child.modelOutput(output_name) param_def = child.algorithm().parameterDefinition( model_output.childOutputName()) if not (param_def.flags() & QgsProcessingParameterDefinition.FlagOptional): self.requiredCheck.setEnabled(False) self.requiredCheck.setChecked(True) self.advancedCheck.setEnabled(False) self.advancedCheck.setChecked(False) self.verticalLayout.addStretch() w = QWidget() w.setLayout(self.verticalLayout) self.tab.addTab(w, self.tr('Properties')) self.commentLayout = QVBoxLayout() self.commentEdit = QTextEdit() self.commentEdit.setAcceptRichText(False) self.commentLayout.addWidget(self.commentEdit, 1) hl = QHBoxLayout() hl.setContentsMargins(0, 0, 0, 0) hl.addWidget(QLabel(self.tr('Color'))) self.comment_color_button = QgsColorButton() self.comment_color_button.setAllowOpacity(True) self.comment_color_button.setWindowTitle(self.tr('Comment Color')) self.comment_color_button.setShowNull(True, self.tr('Default')) hl.addWidget(self.comment_color_button) self.commentLayout.addLayout(hl) w2 = QWidget() w2.setLayout(self.commentLayout) self.tab.addTab(w2, self.tr('Comments')) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.mainLayout.addWidget(self.buttonBox) self.setLayout(self.mainLayout) def setComments(self, text): self.commentEdit.setPlainText(text) def comments(self): return self.commentEdit.toPlainText() def setCommentColor(self, color): if color.isValid(): self.comment_color_button.setColor(color) else: self.comment_color_button.setToNull() def commentColor(self): return self.comment_color_button.color( ) if not self.comment_color_button.isNull() else QColor() def accept(self): description = self.nameTextBox.text() if description.strip() == '': QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Invalid parameter name')) return if self.param is None: validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' safeName = ''.join(c for c in description if c in validChars) name = safeName.lower() i = 2 while self.alg.parameterDefinition(name): name = safeName.lower() + str(i) i += 1 else: name = self.param.name() if (self.paramType == parameters.PARAMETER_TABLE_FIELD or isinstance(self.param, QgsProcessingParameterField)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() datatype = self.datatypeCombo.currentData() default = self.defaultTextBox.text() if not default: default = None self.param = QgsProcessingParameterField( name, description, defaultValue=default, parentLayerParameterName=parent, type=datatype, allowMultiple=self.multipleCheck.isChecked()) elif (self.paramType == parameters.PARAMETER_BAND or isinstance(self.param, QgsProcessingParameterBand)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() self.param = QgsProcessingParameterBand(name, description, None, parent) elif (self.paramType == parameters.PARAMETER_MAP_LAYER or isinstance(self.param, QgsProcessingParameterMapLayer)): self.param = QgsProcessingParameterMapLayer( name, description, types=[self.datatypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_RASTER or isinstance(self.param, QgsProcessingParameterRasterLayer)): self.param = QgsProcessingParameterRasterLayer(name, description) elif (self.paramType == parameters.PARAMETER_TABLE or isinstance(self.param, QgsProcessingParameterVectorLayer)): self.param = QgsProcessingParameterVectorLayer( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_VECTOR or isinstance(self.param, QgsProcessingParameterFeatureSource)): self.param = QgsProcessingParameterFeatureSource( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_MULTIPLE or isinstance(self.param, QgsProcessingParameterMultipleLayers)): self.param = QgsProcessingParameterMultipleLayers( name, description, self.datatypeCombo.currentData()) elif (self.paramType == parameters.PARAMETER_DISTANCE or isinstance(self.param, QgsProcessingParameterDistance)): self.param = QgsProcessingParameterDistance( name, description, self.defaultTextBox.text()) try: vmin = self.minTextBox.text().strip() if not vmin == '': self.param.setMinimum(float(vmin)) vmax = self.maxTextBox.text().strip() if not vmax == '': self.param.setMaximum(float(vmax)) except: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() if parent: self.param.setParentParameterName(parent) elif (self.paramType == parameters.PARAMETER_SCALE or isinstance(self.param, QgsProcessingParameterScale)): self.param = QgsProcessingParameterScale( name, description, self.defaultTextBox.text()) elif (self.paramType == parameters.PARAMETER_NUMBER or isinstance(self.param, QgsProcessingParameterNumber)): type = self.type_combo.currentData() self.param = QgsProcessingParameterNumber( name, description, type, self.defaultTextBox.text()) try: vmin = self.minTextBox.text().strip() if not vmin == '': self.param.setMinimum(float(vmin)) vmax = self.maxTextBox.text().strip() if not vmax == '': self.param.setMaximum(float(vmax)) except: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return # Destination parameter elif (isinstance(self.param, QgsProcessingParameterFeatureSink)): self.param = QgsProcessingParameterFeatureSink( name=name, description=self.param.description(), type=self.param.dataType(), defaultValue=self.defaultWidget.value()) elif (isinstance(self.param, QgsProcessingParameterFileDestination)): self.param = QgsProcessingParameterFileDestination( name=name, description=self.param.description(), fileFilter=self.param.fileFilter(), defaultValue=self.defaultWidget.value()) elif (isinstance(self.param, QgsProcessingParameterFolderDestination)): self.param = QgsProcessingParameterFolderDestination( name=name, description=self.param.description(), defaultValue=self.defaultWidget.value()) elif (isinstance(self.param, QgsProcessingParameterRasterDestination)): self.param = QgsProcessingParameterRasterDestination( name=name, description=self.param.description(), defaultValue=self.defaultWidget.value()) elif (isinstance(self.param, QgsProcessingParameterVectorDestination)): self.param = QgsProcessingParameterVectorDestination( name=name, description=self.param.description(), type=self.param.dataType(), defaultValue=self.defaultWidget.value()) else: if self.paramType: typeId = self.paramType else: typeId = self.param.type() paramTypeDef = QgsApplication.instance().processingRegistry( ).parameterType(typeId) if not paramTypeDef: msg = self.tr( 'The parameter `{}` is not registered, are you missing a required plugin?' .format(typeId)) raise UndefinedParameterException(msg) self.param = paramTypeDef.create(name) self.param.setDescription(description) self.param.setMetadata(paramTypeDef.metadata()) if not self.requiredCheck.isChecked(): self.param.setFlags( self.param.flags() | QgsProcessingParameterDefinition.FlagOptional) else: self.param.setFlags( self.param.flags() & ~QgsProcessingParameterDefinition.FlagOptional) if self.advancedCheck.isChecked(): self.param.setFlags( self.param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) else: self.param.setFlags( self.param.flags() & ~QgsProcessingParameterDefinition.FlagAdvanced) settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.accept(self) def reject(self): self.param = None settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.reject(self)
class ModelerParametersWidget(QWidget): def __init__(self, alg, model, algName=None, configuration=None, dialog=None, context=None): super().__init__() self._alg = alg # The algorithm to define in this dialog. It is an instance of QgsProcessingAlgorithm self.model = model # The model this algorithm is going to be added to. It is an instance of QgsProcessingModelAlgorithm self.childId = algName # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self.configuration = configuration self.context = context self.dialog = dialog self.widget = ModelerParametersPanelWidget(alg, model, algName, configuration, dialog, context) class ContextGenerator(QgsProcessingContextGenerator): def __init__(self, context): super().__init__() self.processing_context = context def processingContext(self): return self.processing_context self.context_generator = ContextGenerator(self.context) self.setupUi() self.params = None def algorithm(self): return self._alg def switchToCommentTab(self): self.tab.setCurrentIndex(1) self.commentEdit.setFocus() self.commentEdit.selectAll() def setupUi(self): self.mainLayout = QVBoxLayout() self.mainLayout.setContentsMargins(0, 0, 0, 0) self.tab = QTabWidget() self.mainLayout.addWidget(self.tab) self.param_widget = QgsPanelWidgetStack() self.widget.setDockMode(True) self.param_widget.setMainPanel(self.widget) self.tab.addTab(self.param_widget, self.tr('Properties')) self.commentLayout = QVBoxLayout() self.commentEdit = QTextEdit() self.commentEdit.setAcceptRichText(False) self.commentLayout.addWidget(self.commentEdit, 1) hl = QHBoxLayout() hl.setContentsMargins(0, 0, 0, 0) hl.addWidget(QLabel(self.tr('Color'))) self.comment_color_button = QgsColorButton() self.comment_color_button.setAllowOpacity(True) self.comment_color_button.setWindowTitle(self.tr('Comment Color')) self.comment_color_button.setShowNull(True, self.tr('Default')) hl.addWidget(self.comment_color_button) self.commentLayout.addLayout(hl) w2 = QWidget() w2.setLayout(self.commentLayout) self.tab.addTab(w2, self.tr('Comments')) self.setLayout(self.mainLayout) def setComments(self, text): self.commentEdit.setPlainText(text) def comments(self): return self.commentEdit.toPlainText() def setCommentColor(self, color): if color.isValid(): self.comment_color_button.setColor(color) else: self.comment_color_button.setToNull() def commentColor(self): return self.comment_color_button.color() if not self.comment_color_button.isNull() else QColor() def getAvailableDependencies(self): return self.widget.getAvailableDependencies() def getDependenciesPanel(self): return self.widget.getDependenciesPanel() def getAvailableValuesOfType(self, paramType, outTypes=[], dataTypes=[]): return self.widget.getAvailableValuesOfType(paramType, outTypes, dataTypes) def resolveValueDescription(self, value): return self.widget.resolveValueDescription(value) def setPreviousValues(self): self.widget.setPreviousValues() def createAlgorithm(self): alg = self.widget.createAlgorithm() if alg: alg.comment().setDescription(self.comments()) alg.comment().setColor(self.commentColor()) return alg
class ModelerParameterDefinitionDialog(QDialog): @staticmethod def use_legacy_dialog(param=None, paramType=None): if isinstance(param, QgsProcessingDestinationParameter): return True # yay, use new API! return False def __init__(self, alg, paramType=None, param=None): self.alg = alg self.paramType = paramType self.param = param QDialog.__init__(self) self.setModal(True) self.setupUi() settings = QgsSettings() self.restoreGeometry( settings.value( "/Processing/modelParametersDefinitionDialogGeometry", QByteArray())) def closeEvent(self, event): settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) super(ModelerParameterDefinitionDialog, self).closeEvent(event) def switchToCommentTab(self): self.tab.setCurrentIndex(1) self.commentEdit.setFocus() self.commentEdit.selectAll() def setupUi(self): type_metadata = QgsApplication.processingRegistry().parameterType( self.param.type() if self.param else self.paramType) self.setWindowTitle( self.tr('{} Parameter Definition').format(type_metadata.name())) self.mainLayout = QVBoxLayout() self.tab = QTabWidget() self.mainLayout.addWidget(self.tab) self.setMinimumWidth(300) self.verticalLayout = QVBoxLayout() self.label = QLabel(self.tr('Parameter name')) self.verticalLayout.addWidget(self.label) self.nameTextBox = QLineEdit() self.verticalLayout.addWidget(self.nameTextBox) if isinstance(self.param, QgsProcessingParameterDefinition): self.nameTextBox.setText(self.param.description()) if isinstance(self.param, QgsProcessingDestinationParameter): self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultWidget = QgsProcessingLayerOutputDestinationWidget( self.param, defaultSelection=True) self.verticalLayout.addWidget(self.defaultWidget) self.verticalLayout.addSpacing(20) self.requiredCheck = QCheckBox() self.requiredCheck.setText(self.tr('Mandatory')) self.requiredCheck.setChecked(True) if self.param is not None: self.requiredCheck.setChecked( not self.param.flags() & QgsProcessingParameterDefinition.FlagOptional) self.verticalLayout.addWidget(self.requiredCheck) self.advancedCheck = QCheckBox() self.advancedCheck.setText(self.tr('Advanced')) self.advancedCheck.setChecked(False) if self.param is not None: self.advancedCheck.setChecked( self.param.flags() & QgsProcessingParameterDefinition.FlagAdvanced) self.verticalLayout.addWidget(self.advancedCheck) # If child algorithm output is mandatory, disable checkbox if isinstance(self.param, QgsProcessingDestinationParameter): child = self.alg.childAlgorithms()[self.param.metadata() ['_modelChildId']] model_output = child.modelOutput( self.param.metadata()['_modelChildOutputName']) param_def = child.algorithm().parameterDefinition( model_output.childOutputName()) if not (param_def.flags() & QgsProcessingParameterDefinition.FlagOptional): self.requiredCheck.setEnabled(False) self.requiredCheck.setChecked(True) self.advancedCheck.setEnabled(False) self.advancedCheck.setChecked(False) self.verticalLayout.addStretch() w = QWidget() w.setLayout(self.verticalLayout) self.tab.addTab(w, self.tr('Properties')) self.commentLayout = QVBoxLayout() self.commentEdit = QTextEdit() self.commentEdit.setAcceptRichText(False) self.commentLayout.addWidget(self.commentEdit, 1) hl = QHBoxLayout() hl.setContentsMargins(0, 0, 0, 0) hl.addWidget(QLabel(self.tr('Color'))) self.comment_color_button = QgsColorButton() self.comment_color_button.setAllowOpacity(True) self.comment_color_button.setWindowTitle(self.tr('Comment Color')) self.comment_color_button.setShowNull(True, self.tr('Default')) hl.addWidget(self.comment_color_button) self.commentLayout.addLayout(hl) w2 = QWidget() w2.setLayout(self.commentLayout) self.tab.addTab(w2, self.tr('Comments')) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.mainLayout.addWidget(self.buttonBox) self.setLayout(self.mainLayout) def setComments(self, text): self.commentEdit.setPlainText(text) def comments(self): return self.commentEdit.toPlainText() def setCommentColor(self, color): if color.isValid(): self.comment_color_button.setColor(color) else: self.comment_color_button.setToNull() def commentColor(self): return self.comment_color_button.color( ) if not self.comment_color_button.isNull() else QColor() def accept(self): description = self.nameTextBox.text() if description.strip() == '': QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Invalid parameter name')) return validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' safeName = ''.join(c for c in description if c in validChars) name = safeName.lower() # Destination parameter if (isinstance(self.param, QgsProcessingParameterFeatureSink)): self.param = QgsProcessingParameterFeatureSink( name=name, description=description, type=self.param.dataType(), defaultValue=self.defaultWidget.value()) elif (isinstance(self.param, QgsProcessingParameterFileDestination)): self.param = QgsProcessingParameterFileDestination( name=name, description=description, fileFilter=self.param.fileFilter(), defaultValue=self.defaultWidget.value()) elif (isinstance(self.param, QgsProcessingParameterFolderDestination)): self.param = QgsProcessingParameterFolderDestination( name=name, description=description, defaultValue=self.defaultWidget.value()) elif (isinstance(self.param, QgsProcessingParameterRasterDestination)): self.param = QgsProcessingParameterRasterDestination( name=name, description=description, defaultValue=self.defaultWidget.value()) elif (isinstance(self.param, QgsProcessingParameterVectorDestination)): self.param = QgsProcessingParameterVectorDestination( name=name, description=description, type=self.param.dataType(), defaultValue=self.defaultWidget.value()) else: if self.paramType: typeId = self.paramType else: typeId = self.param.type() paramTypeDef = QgsApplication.instance().processingRegistry( ).parameterType(typeId) if not paramTypeDef: msg = self.tr( 'The parameter `{}` is not registered, are you missing a required plugin?' .format(typeId)) raise UndefinedParameterException(msg) self.param = paramTypeDef.create(name) self.param.setDescription(description) self.param.setMetadata(paramTypeDef.metadata()) if not self.requiredCheck.isChecked(): self.param.setFlags( self.param.flags() | QgsProcessingParameterDefinition.FlagOptional) else: self.param.setFlags( self.param.flags() & ~QgsProcessingParameterDefinition.FlagOptional) if self.advancedCheck.isChecked(): self.param.setFlags( self.param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) else: self.param.setFlags( self.param.flags() & ~QgsProcessingParameterDefinition.FlagAdvanced) settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.accept(self) def reject(self): self.param = None settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.reject(self)