def testNulling(self): """ Test clearing colors to null """ # 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)) spy_changed = QSignalSpy(button.colorChanged) spy_cleared = QSignalSpy(button.cleared) button.setColor(QColor(50, 100, 200, 255)) self.assertEqual(button.color(), QColor(50, 100, 200, 255)) self.assertEqual(len(spy_changed), 1) self.assertEqual(len(spy_cleared), 0) # now set to null button.setToNull() self.assertEqual(button.color(), QColor()) self.assertEqual(len(spy_changed), 2) self.assertEqual(len(spy_cleared), 1) button.setToNull() self.assertEqual(button.color(), QColor()) # should not be refired, the color wasn't changed self.assertEqual(len(spy_changed), 2) # SHOULD be refired self.assertEqual(len(spy_cleared), 2)
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 getParams(configure_exporter_action=None): accentColor = QgsColorButton() accentColor.setColor(QColor(0, 0, 0)) backgroundColor = QgsColorButton() backgroundColor.setColor(QColor(248, 248, 248)) params = { "Appearance": { "Add layers list": ("None", "Collapsed", "Expanded"), "Match project CRS": False, "Add address search": False, "Layer search": ("None", "placeholder"), "Measure tool": ("None", "Metric", "Imperial"), "Show popups on hover": False, "Highlight on hover": False, "Geolocate user": False, "Template": getTemplates(), "Widget Icon": accentColor, "Widget Background": backgroundColor }, "Data export": { "Precision": ("maintain", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"), "Minify GeoJSON files": True, "Mapping library location": ("Local", "CDN"), "Use debug libraries": False }, "Scale/Zoom": { "Extent": ("Canvas extent", "Fit to layers extent"), "Restrict to extent": False, "Max zoom level": ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28"), "Min zoom level": ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28"), } } if configure_exporter_action: params["Data export"]["Exporter"] = { 'option': EXPORTER_REGISTRY.getOptions(), 'action': configure_exporter_action } else: params["Data export"]["Exporter"] = EXPORTER_REGISTRY.getOptions() return params
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 getParams(configure_exporter_action=None): accentColor = QgsColorButton() accentColor.setColor(QColor(0, 0, 0)) backgroundColor = QgsColorButton() backgroundColor.setColor(QColor(248, 248, 248)) params = { "Appearance": { "Add layers list": ("None", "Collapsed", "Expanded"), "Match project CRS": False, "Add address search": False, "Layer search": ("None", "placeholder"), "Measure tool": ("None", "Metric", "Imperial"), "Show popups on hover": False, "Highlight on hover": False, "Geolocate user": False, "Template": getTemplates(), "Widget Icon": accentColor, "Widget Background": backgroundColor }, "Data export": { "Precision": ("maintain", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"), "Minify GeoJSON files": True }, "Scale/Zoom": { "Extent": ("Canvas extent", "Fit to layers extent"), "Restrict to extent": False, "Max zoom level": ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28"), "Min zoom level": ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28"), } } if configure_exporter_action: params["Data export"]["Exporter"] = {'option': EXPORTER_REGISTRY.getOptions(), 'action': configure_exporter_action} else: params["Data export"]["Exporter"] = EXPORTER_REGISTRY.getOptions() return params
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))
class Ui_Mapmashup(object): def setupUi(self, Mapmashup): Mapmashup.setObjectName("Mapmashup") Mapmashup.resize(327, 427) self.verticalLayout = QtWidgets.QVBoxLayout(Mapmashup) self.verticalLayout.setObjectName("verticalLayout") self.hlImageFolder = QtWidgets.QHBoxLayout() self.hlImageFolder.setObjectName("hlImageFolder") self.leImageFolder = QtWidgets.QLineEdit(Mapmashup) self.leImageFolder.setObjectName("leImageFolder") self.hlImageFolder.addWidget(self.leImageFolder) self.butBrowseImg = QtWidgets.QPushButton(Mapmashup) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.butBrowseImg.sizePolicy().hasHeightForWidth()) self.butBrowseImg.setSizePolicy(sizePolicy) self.butBrowseImg.setMinimumSize(QtCore.QSize(100, 0)) self.butBrowseImg.setMaximumSize(QtCore.QSize(100, 16777215)) self.butBrowseImg.setObjectName("butBrowseImg") self.hlImageFolder.addWidget(self.butBrowseImg) self.verticalLayout.addLayout(self.hlImageFolder) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.leRegistrationFolder = QtWidgets.QLineEdit(Mapmashup) self.leRegistrationFolder.setObjectName("leRegistrationFolder") self.horizontalLayout_2.addWidget(self.leRegistrationFolder) self.butBrowseReg = QtWidgets.QPushButton(Mapmashup) sizePolicy = QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.butBrowseReg.sizePolicy().hasHeightForWidth()) self.butBrowseReg.setSizePolicy(sizePolicy) self.butBrowseReg.setMinimumSize(QtCore.QSize(100, 0)) self.butBrowseReg.setMaximumSize(QtCore.QSize(100, 16777215)) self.butBrowseReg.setObjectName("butBrowseReg") self.horizontalLayout_2.addWidget(self.butBrowseReg) self.verticalLayout.addLayout(self.horizontalLayout_2) self.horizontalLayout_5 = QtWidgets.QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.cboRegistrations = QtWidgets.QComboBox(Mapmashup) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.cboRegistrations.sizePolicy().hasHeightForWidth()) self.cboRegistrations.setSizePolicy(sizePolicy) self.cboRegistrations.setObjectName("cboRegistrations") self.horizontalLayout_5.addWidget(self.cboRegistrations) self.butRefresh = QtWidgets.QPushButton(Mapmashup) sizePolicy = QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.butRefresh.sizePolicy().hasHeightForWidth()) self.butRefresh.setSizePolicy(sizePolicy) self.butRefresh.setMinimumSize(QtCore.QSize(100, 0)) self.butRefresh.setMaximumSize(QtCore.QSize(100, 16777215)) self.butRefresh.setObjectName("butRefresh") self.horizontalLayout_5.addWidget(self.butRefresh) self.verticalLayout.addLayout(self.horizontalLayout_5) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.label_2 = QtWidgets.QLabel(Mapmashup) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) self.leName = QtWidgets.QLineEdit(Mapmashup) self.leName.setObjectName("leName") self.horizontalLayout.addWidget(self.leName) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.label = QtWidgets.QLabel(Mapmashup) self.label.setObjectName("label") self.horizontalLayout_3.addWidget(self.label) self.hsTransparency = QtWidgets.QSlider(Mapmashup) self.hsTransparency.setOrientation(QtCore.Qt.Horizontal) self.hsTransparency.setTickPosition(QtWidgets.QSlider.TicksBelow) self.hsTransparency.setTickInterval(10) self.hsTransparency.setObjectName("hsTransparency") self.horizontalLayout_3.addWidget(self.hsTransparency) self.verticalLayout.addLayout(self.horizontalLayout_3) self.groupBox = QtWidgets.QGroupBox(Mapmashup) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.groupBox.sizePolicy().hasHeightForWidth()) self.groupBox.setSizePolicy(sizePolicy) self.groupBox.setMinimumSize(QtCore.QSize(0, 61)) self.groupBox.setMaximumSize(QtCore.QSize(3000, 61)) self.groupBox.setObjectName("groupBox") self.cbTransparentColour = QtWidgets.QCheckBox(self.groupBox) self.cbTransparentColour.setGeometry(QtCore.QRect(10, 15, 211, 17)) self.cbTransparentColour.setObjectName("cbTransparentColour") self.label_3 = QtWidgets.QLabel(self.groupBox) self.label_3.setGeometry(QtCore.QRect(10, 35, 56, 20)) self.label_3.setObjectName("label_3") self.mcbTransparentColour = QgsColorButton(self.groupBox) self.mcbTransparentColour.setGeometry(QtCore.QRect(43, 33, 61, 25)) self.mcbTransparentColour.setColor(QtGui.QColor(255, 255, 255)) self.mcbTransparentColour.setDefaultColor(QtGui.QColor(255, 255, 255)) self.mcbTransparentColour.setObjectName("mcbTransparentColour") self.verticalLayout.addWidget(self.groupBox) self.horizontalLayout_6 = QtWidgets.QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.leStyleFile = QtWidgets.QLineEdit(Mapmashup) self.leStyleFile.setObjectName("leStyleFile") self.horizontalLayout_6.addWidget(self.leStyleFile) self.pbBrowseStyleFile = QtWidgets.QPushButton(Mapmashup) self.pbBrowseStyleFile.setMinimumSize(QtCore.QSize(100, 0)) self.pbBrowseStyleFile.setObjectName("pbBrowseStyleFile") self.horizontalLayout_6.addWidget(self.pbBrowseStyleFile) self.verticalLayout.addLayout(self.horizontalLayout_6) self.cbApplyStyle = QtWidgets.QCheckBox(Mapmashup) self.cbApplyStyle.setObjectName("cbApplyStyle") self.verticalLayout.addWidget(self.cbApplyStyle) self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.butLoadImage = QtWidgets.QPushButton(Mapmashup) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.butLoadImage.sizePolicy().hasHeightForWidth()) self.butLoadImage.setSizePolicy(sizePolicy) self.butLoadImage.setMinimumSize(QtCore.QSize(30, 30)) self.butLoadImage.setMaximumSize(QtCore.QSize(30, 30)) self.butLoadImage.setText("") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("images/mashup.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.butLoadImage.setIcon(icon) self.butLoadImage.setIconSize(QtCore.QSize(26, 26)) self.butLoadImage.setObjectName("butLoadImage") self.horizontalLayout_4.addWidget(self.butLoadImage) self.butLoadImageFile = QtWidgets.QPushButton(Mapmashup) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.butLoadImageFile.sizePolicy().hasHeightForWidth()) self.butLoadImageFile.setSizePolicy(sizePolicy) self.butLoadImageFile.setMinimumSize(QtCore.QSize(30, 30)) self.butLoadImageFile.setMaximumSize(QtCore.QSize(30, 30)) self.butLoadImageFile.setText("") icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap("images/mashup2.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.butLoadImageFile.setIcon(icon1) self.butLoadImageFile.setIconSize(QtCore.QSize(26, 26)) self.butLoadImageFile.setObjectName("butLoadImageFile") self.horizontalLayout_4.addWidget(self.butLoadImageFile) self.butLoadImageBrowse = QtWidgets.QPushButton(Mapmashup) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.butLoadImageBrowse.sizePolicy().hasHeightForWidth()) self.butLoadImageBrowse.setSizePolicy(sizePolicy) self.butLoadImageBrowse.setMinimumSize(QtCore.QSize(30, 30)) self.butLoadImageBrowse.setMaximumSize(QtCore.QSize(30, 30)) self.butLoadImageBrowse.setText("") icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap("images/mashup3.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.butLoadImageBrowse.setIcon(icon2) self.butLoadImageBrowse.setIconSize(QtCore.QSize(26, 26)) self.butLoadImageBrowse.setObjectName("butLoadImageBrowse") self.horizontalLayout_4.addWidget(self.butLoadImageBrowse) self.butClearLast = QtWidgets.QPushButton(Mapmashup) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.butClearLast.sizePolicy().hasHeightForWidth()) self.butClearLast.setSizePolicy(sizePolicy) self.butClearLast.setMinimumSize(QtCore.QSize(30, 30)) self.butClearLast.setMaximumSize(QtCore.QSize(30, 30)) self.butClearLast.setText("") icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap("images/removelayer.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.butClearLast.setIcon(icon3) self.butClearLast.setIconSize(QtCore.QSize(26, 26)) self.butClearLast.setObjectName("butClearLast") self.horizontalLayout_4.addWidget(self.butClearLast) self.butClear = QtWidgets.QPushButton(Mapmashup) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.butClear.sizePolicy().hasHeightForWidth()) self.butClear.setSizePolicy(sizePolicy) self.butClear.setMinimumSize(QtCore.QSize(30, 30)) self.butClear.setMaximumSize(QtCore.QSize(30, 30)) self.butClear.setText("") icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap("images/removelayers.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.butClear.setIcon(icon4) self.butClear.setIconSize(QtCore.QSize(26, 26)) self.butClear.setObjectName("butClear") self.horizontalLayout_4.addWidget(self.butClear) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem) self.butHelp = QtWidgets.QPushButton(Mapmashup) self.butHelp.setMinimumSize(QtCore.QSize(30, 30)) self.butHelp.setMaximumSize(QtCore.QSize(30, 30)) self.butHelp.setText("") icon5 = QtGui.QIcon() icon5.addPixmap(QtGui.QPixmap("images/info.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.butHelp.setIcon(icon5) self.butHelp.setIconSize(QtCore.QSize(24, 24)) self.butHelp.setObjectName("butHelp") self.horizontalLayout_4.addWidget(self.butHelp) self.butGithub = QtWidgets.QPushButton(Mapmashup) self.butGithub.setMinimumSize(QtCore.QSize(30, 30)) self.butGithub.setMaximumSize(QtCore.QSize(30, 30)) self.butGithub.setText("") icon6 = QtGui.QIcon() icon6.addPixmap(QtGui.QPixmap("images/github.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.butGithub.setIcon(icon6) self.butGithub.setIconSize(QtCore.QSize(24, 24)) self.butGithub.setObjectName("butGithub") self.horizontalLayout_4.addWidget(self.butGithub) self.verticalLayout.addLayout(self.horizontalLayout_4) spacerItem1 = QtWidgets.QSpacerItem(20, 150, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem1) self.groupBox.raise_() self.cbApplyStyle.raise_() self.retranslateUi(Mapmashup) QtCore.QMetaObject.connectSlotsByName(Mapmashup) def retranslateUi(self, Mapmashup): _translate = QtCore.QCoreApplication.translate Mapmashup.setWindowTitle(_translate("Mapmashup", "FSC QGIS plugin")) self.leImageFolder.setToolTip( _translate("Mapmashup", "Path of folder for temp image files")) self.butBrowseImg.setToolTip( _translate("Mapmashup", "Browse for image folder")) self.butBrowseImg.setText(_translate("Mapmashup", "Image folder")) self.leRegistrationFolder.setToolTip( _translate("Mapmashup", "Folder where WLD files are kept")) self.butBrowseReg.setToolTip( _translate("Mapmashup", "Browse for folder containing WLD files")) self.butBrowseReg.setText( _translate("Mapmashup", "Registration folder")) self.cboRegistrations.setToolTip( _translate("Mapmashup", "Select WLD registration info")) self.butRefresh.setToolTip( _translate("Mapmashup", "Refresh the list of WLD files")) self.butRefresh.setText(_translate("Mapmashup", "Refresh")) self.label_2.setText(_translate("Mapmashup", "Layer name")) self.leName.setToolTip( _translate("Mapmashup", "Text to be used in layer name")) self.label.setText(_translate("Mapmashup", "Global transparency")) self.hsTransparency.setToolTip( _translate("Mapmashup", "Set the layer\'s global transparency")) self.groupBox.setTitle(_translate("Mapmashup", "Transparent colour")) self.cbTransparentColour.setText( _translate("Mapmashup", "Set transparent background colour")) self.label_3.setText(_translate("Mapmashup", "Colour")) self.mcbTransparentColour.setToolTip( _translate("Mapmashup", "Use this button to select transparent colour")) self.mcbTransparentColour.setColorDialogTitle( _translate("Mapmashup", "Select transparent colour")) self.leStyleFile.setToolTip( _translate("Mapmashup", "Path of style file to apply to created maps")) self.pbBrowseStyleFile.setText( _translate("Mapmashup", "Browse style file")) self.cbApplyStyle.setText(_translate("Mapmashup", "Apply style")) self.butLoadImage.setToolTip( _translate( "Mapmashup", "Paste image from clipboard to map with specified registration" )) self.butLoadImageFile.setToolTip( _translate( "Mapmashup", "Paste most recent image from image folder to map with specified registration" )) self.butLoadImageBrowse.setToolTip( _translate( "Mapmashup", "Browse for image to paste into map with specified registration" )) self.butClearLast.setToolTip( _translate("Mapmashup", "Remove last mashed map")) self.butClear.setToolTip( _translate("Mapmashup", "Remove all mashed maps")) self.butHelp.setToolTip( _translate( "Mapmashup", "<html><head/><body><p><span style=\" font-size:12pt;\">Get more information about this tool and help on using it. This links to a webpage with up-to-date information about the tool. </span></p></body></html>" )) self.butGithub.setToolTip( _translate( "Mapmashup", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600;\">Report an issue with this tool.</span><span style=\" font-size:12pt;\"> Using this channel is the best way to get attention quickly. Issues can be bug reports, enhancement requests or just questions. Anyone can view current issues, but to add a new issue you will need to sign up for a free Github account (very easy).</span></p></body></html>" ))
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 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 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 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 SaveFigureDlg(QDialog): def __init__(self, dFigureParams, parent=None): super(SaveFigureDlg, self).__init__(parent) self.dFigureParams = dFigureParams layout = QVBoxLayout() # output format settings grpFormatSettings = QGroupBox("Output format") lytFormatSettings = QGridLayout() # format lytFormatSettings.addWidget(QLabel("File format"), 0, 0, 1, 1) self.cmbFileFormat = QComboBox() self.cmbFileFormat.insertItems(0, ltFileFormats) sFileFormat = self.dPlotStyles["file_format"] iCurrFileFrmtNdx = ltFileFormats.index( sFileFormat) if sFileFormat in ltFileFormats else 0 self.cmbFileFormat.setCurrentIndex(iCurrFileFrmtNdx) lytFormatSettings.addWidget(self.cmbFileFormat, 0, 1, 1, 1) # dpi (for rasters) lytFormatSettings.addWidget(QLabel("Dpi (for rasters"), 1, 0, 1, 1) self.cmbDpiResolution = QComboBox() self.cmbDpiResolution.insertItems(0, liDpiResolutions) iCurrDpiResolution = self.dPlotStyles["dpi_resolution"] iCurrDpiResolNdx = ltFileFormats.index( iCurrDpiResolution) if iCurrDpiResolution in ltFileFormats else 0 self.cmbDpiResolution.setCurrentIndex(iCurrDpiResolNdx) lytFormatSettings.addWidget(self.cmbDpiResolution, 1, 1, 1, 1) # set/add to layout grpFormatSettings.setLayout(lytFormatSettings) layout.addWidget(grpFormatSettings) # output file path grpPoles = QGroupBox("Poles") lytPoles = QGridLayout() # marker color lytPoles.addWidget(QLabel("Marker color"), 0, 0, 1, 1) self.btnPointColor = QgsColorButton() point_color = self.dPlotStyles["marker_color"] self.btnPointColor.setColor(QColor(point_color)) lytPoles.addWidget(self.btnPointColor, 0, 1, 1, 1) # marker style lytPoles.addWidget(QLabel("Marker style"), 0, 2, 1, 1) self.cmbPointStyle = QComboBox() self.cmbPointStyle.insertItems(0, list(ltMarkerStyles.keys())) point_style = self.dPlotStyles["marker_style"] point_style_ndx = list( ltMarkerStyles.keys()).index(point_style) if point_style in list( ltMarkerStyles.keys()) else 0 self.cmbPointStyle.setCurrentIndex(point_style_ndx) lytPoles.addWidget(self.cmbPointStyle, 0, 3, 1, 1) # marker size lytPoles.addWidget(QLabel("Marker size"), 1, 0, 1, 1) lnPointSizes = [2, 4, 6, 8, 10, 15, 20] self.cmbPointSize = QComboBox() ltPointSizeVals = [str(val) + " pt(s)" for val in lnPointSizes] self.cmbPointSize.insertItems(0, ltPointSizeVals) point_size = self.dPlotStyles["marker_size"] point_style_ndx = ltPointSizeVals.index( point_size) if point_size in ltPointSizeVals else 2 self.cmbPointSize.setCurrentIndex(point_style_ndx) lytPoles.addWidget(self.cmbPointSize, 1, 1, 1, 1) # marker transparency lytPoles.addWidget(QLabel("Marker transp."), 1, 2, 1, 1) lnPointTransparencies = [0, 25, 50, 75] self.cmbPointTransp = QComboBox() ltPointTranspPrcntVals = [ str(val) + "%" for val in lnPointTransparencies ] self.cmbPointTransp.insertItems(0, ltPointTranspPrcntVals) point_transp = self.dPlotStyles["marker_transp"] point_transp_ndx = ltPointTranspPrcntVals.index( point_transp) if point_transp in ltPointTranspPrcntVals else 0 self.cmbPointTransp.setCurrentIndex(point_transp_ndx) lytPoles.addWidget(self.cmbPointTransp, 1, 3, 1, 1) # set/add to layout grpPoles.setLayout(lytPoles) layout.addWidget(grpPoles) # ok/cancel stuff btnOk = QPushButton("&OK") btnCancel = QPushButton("Cancel") lytButtons = QHBoxLayout() lytButtons.addStretch() lytButtons.addWidget(btnOk) lytButtons.addWidget(btnCancel) layout.addLayout(lytButtons) btnOk.clicked.connect(self.accept) btnCancel.clicked.connect(self.reject) self.setLayout(layout) self.setWindowTitle("Plot style")
class PlotStyleDlg(QDialog): def __init__(self, dPlotStyles, parent=None): super(PlotStyleDlg, self).__init__(parent) self.dPlotStyles = dPlotStyles settings = QSettings("alberese", "geocouche") layout = QVBoxLayout() # great circle settings grpGreatCircles = QGroupBox("Great circles") lytGreatCircles = QGridLayout() # line color lytGreatCircles.addWidget(QLabel("Line color"), 0, 0, 1, 1) self.btnLineColor = QgsColorButton() line_color = self.dPlotStyles["line_color"] self.btnLineColor.setColor(QColor(line_color)) lytGreatCircles.addWidget(self.btnLineColor, 0, 1, 1, 1) # line style lytGreatCircles.addWidget(QLabel("Line style"), 0, 2, 1, 1) self.cmbLineStyle = QComboBox() self.cmbLineStyle.insertItems(0, ltLineStyles) line_style = self.dPlotStyles["line_style"] line_style_ndx = ltLineStyles.index(line_style) if line_style in ltLineStyles else 0 self.cmbLineStyle.setCurrentIndex(line_style_ndx) lytGreatCircles.addWidget(self.cmbLineStyle, 0, 3, 1, 1) # line thickness lytGreatCircles.addWidget(QLabel("Line width"), 1, 0, 1, 1) self.cmbLineWidth = QComboBox() lnLineThickness = [1, 2, 3, 4, 5, 6] ltLineThicknVals = [str(val) + " pt(s)" for val in lnLineThickness] self.cmbLineWidth.insertItems(0, ltLineThicknVals) line_thickn = self.dPlotStyles["line_width"] line_thickn_ndx = ltLineThicknVals.index(line_thickn) if line_thickn in ltLineThicknVals else 0 self.cmbLineWidth.setCurrentIndex(line_thickn_ndx) lytGreatCircles.addWidget(self.cmbLineWidth, 1, 1, 1, 1) # line transparency lytGreatCircles.addWidget(QLabel("Line transp."), 1, 2, 1, 1) self.cmbLineTransp = QComboBox() lnLineTransparencies = [0, 25, 50, 75] ltLineTranspPrcntVals = [str(val) + "%" for val in lnLineTransparencies] self.cmbLineTransp.insertItems(0, ltLineTranspPrcntVals) line_transp = self.dPlotStyles["line_transp"] line_transp_ndx = ltLineTranspPrcntVals.index(line_transp) if line_transp in ltLineTranspPrcntVals else 0 self.cmbLineTransp.setCurrentIndex(line_transp_ndx) lytGreatCircles.addWidget(self.cmbLineTransp, 1, 3, 1, 1) # set/add to layout grpGreatCircles.setLayout(lytGreatCircles) layout.addWidget(grpGreatCircles) # pole settings grpPoles = QGroupBox("Poles") lytPoles = QGridLayout() # marker color lytPoles.addWidget(QLabel("Marker color"), 0, 0, 1, 1) self.btnPointColor = QgsColorButton() point_color = self.dPlotStyles["marker_color"] self.btnPointColor.setColor(QColor(point_color)) lytPoles.addWidget(self.btnPointColor, 0, 1, 1, 1) # marker style lytPoles.addWidget(QLabel("Marker style"), 0, 2, 1, 1) self.cmbPointStyle = QComboBox() self.cmbPointStyle.insertItems(0, list(ltMarkerStyles.keys())) point_style = self.dPlotStyles["marker_style"] point_style_ndx = list(ltMarkerStyles.keys()).index(point_style) if point_style in list(ltMarkerStyles.keys()) else 0 self.cmbPointStyle.setCurrentIndex(point_style_ndx) lytPoles.addWidget(self.cmbPointStyle, 0, 3, 1, 1) # marker size lytPoles.addWidget(QLabel("Marker size"), 1, 0, 1, 1) lnPointSizes = [2, 4, 6, 8, 10, 15, 20] self.cmbPointSize = QComboBox() ltPointSizeVals = [str(val) + " pt(s)" for val in lnPointSizes] self.cmbPointSize.insertItems(0, ltPointSizeVals) point_size = self.dPlotStyles["marker_size"] point_style_ndx = ltPointSizeVals.index(point_size) if point_size in ltPointSizeVals else 2 self.cmbPointSize.setCurrentIndex(point_style_ndx) lytPoles.addWidget(self.cmbPointSize, 1, 1, 1, 1) # marker transparency lytPoles.addWidget(QLabel("Marker transp."), 1, 2, 1, 1) lnPointTransparencies = [0, 25, 50, 75] self.cmbPointTransp = QComboBox() ltPointTranspPrcntVals = [str(val) + "%" for val in lnPointTransparencies] self.cmbPointTransp.insertItems(0, ltPointTranspPrcntVals) point_transp = self.dPlotStyles["marker_transp"] point_transp_ndx = ltPointTranspPrcntVals.index(point_transp) if point_transp in ltPointTranspPrcntVals else 0 self.cmbPointTransp.setCurrentIndex(point_transp_ndx) lytPoles.addWidget(self.cmbPointTransp, 1, 3, 1, 1) # set/add to layout grpPoles.setLayout(lytPoles) layout.addWidget(grpPoles) # ok/cancel stuff btnOk = QPushButton("&OK") btnCancel = QPushButton("Cancel") lytButtons = QHBoxLayout() lytButtons.addStretch() lytButtons.addWidget(btnOk) lytButtons.addWidget(btnCancel) layout.addLayout(lytButtons) btnOk.clicked.connect(self.accept) btnCancel.clicked.connect(self.reject) self.setLayout(layout) self.setWindowTitle("Plot style")
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 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 Ui_B4UdigNL(object): def setupUi(self, B4UdigNL): B4UdigNL.setObjectName("B4UdigNL") B4UdigNL.resize(324, 432) B4UdigNL.setFocusPolicy(QtCore.Qt.StrongFocus) self.verticalLayout = QtWidgets.QVBoxLayout(B4UdigNL) self.verticalLayout.setObjectName("verticalLayout") self.tabWidget = QtWidgets.QTabWidget(B4UdigNL) self.tabWidget.setEnabled(True) self.tabWidget.setAutoFillBackground(False) self.tabWidget.setElideMode(QtCore.Qt.ElideNone) self.tabWidget.setObjectName("tabWidget") self.messageTab = QtWidgets.QWidget() self.messageTab.setObjectName("messageTab") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.messageTab) self.verticalLayout_4.setObjectName("verticalLayout_4") self.messageBox = QtWidgets.QGroupBox(self.messageTab) self.messageBox.setObjectName("messageBox") self.gridLayout = QtWidgets.QGridLayout(self.messageBox) self.gridLayout.setObjectName("gridLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.openMsgButton = QtWidgets.QPushButton(self.messageBox) self.openMsgButton.setObjectName("openMsgButton") self.horizontalLayout.addWidget(self.openMsgButton) self.openArchiveButton = QtWidgets.QPushButton(self.messageBox) self.openArchiveButton.setObjectName("openArchiveButton") self.horizontalLayout.addWidget(self.openArchiveButton) spacerItem = QtWidgets.QSpacerItem(68, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) self.msgListWidget = QtWidgets.QListWidget(self.messageBox) self.msgListWidget.setMinimumSize(QtCore.QSize(100, 40)) self.msgListWidget.setMaximumSize(QtCore.QSize(16777215, 60)) self.msgListWidget.setObjectName("msgListWidget") self.gridLayout.addWidget(self.msgListWidget, 1, 0, 1, 1) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.gotoButton = QtWidgets.QPushButton(self.messageBox) self.gotoButton.setObjectName("gotoButton") self.horizontalLayout_2.addWidget(self.gotoButton) self.bestScaleButton = QtWidgets.QPushButton(self.messageBox) self.bestScaleButton.setObjectName("bestScaleButton") self.horizontalLayout_2.addWidget(self.bestScaleButton) self.removeMsgButton = QtWidgets.QPushButton(self.messageBox) self.removeMsgButton.setObjectName("removeMsgButton") self.horizontalLayout_2.addWidget(self.removeMsgButton) spacerItem1 = QtWidgets.QSpacerItem(78, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem1) self.gridLayout.addLayout(self.horizontalLayout_2, 2, 0, 1, 1) self.verticalLayout_4.addWidget(self.messageBox) self.additionsBox = QtWidgets.QGroupBox(self.messageTab) self.additionsBox.setMaximumSize(QtCore.QSize(16777215, 300)) self.additionsBox.setObjectName("additionsBox") self.gridLayout_2 = QtWidgets.QGridLayout(self.additionsBox) self.gridLayout_2.setObjectName("gridLayout_2") self.treeWidget = QtWidgets.QTreeWidget(self.additionsBox) self.treeWidget.setMinimumSize(QtCore.QSize(100, 100)) self.treeWidget.setMaximumSize(QtCore.QSize(16777215, 250)) self.treeWidget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection) self.treeWidget.setObjectName("treeWidget") self.treeWidget.headerItem().setText(0, "1") self.gridLayout_2.addWidget(self.treeWidget, 0, 0, 1, 1) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.openDocButton = QtWidgets.QPushButton(self.additionsBox) self.openDocButton.setObjectName("openDocButton") self.horizontalLayout_3.addWidget(self.openDocButton) spacerItem2 = QtWidgets.QSpacerItem(168, 17, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem2) self.gridLayout_2.addLayout(self.horizontalLayout_3, 1, 0, 1, 1) self.verticalLayout_4.addWidget(self.additionsBox) spacerItem3 = QtWidgets.QSpacerItem(17, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout_4.addItem(spacerItem3) self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.saveButton = QtWidgets.QPushButton(self.messageTab) self.saveButton.setObjectName("saveButton") self.horizontalLayout_4.addWidget(self.saveButton) spacerItem4 = QtWidgets.QSpacerItem(13, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem4) self.helpButton = QtWidgets.QPushButton(self.messageTab) self.helpButton.setObjectName("helpButton") self.horizontalLayout_4.addWidget(self.helpButton) self.closeButton = QtWidgets.QPushButton(self.messageTab) self.closeButton.setObjectName("closeButton") self.horizontalLayout_4.addWidget(self.closeButton) self.verticalLayout_4.addLayout(self.horizontalLayout_4) self.tabWidget.addTab(self.messageTab, "") self.ThemesTab = QtWidgets.QWidget() self.ThemesTab.setObjectName("ThemesTab") self.gridLayout_3 = QtWidgets.QGridLayout(self.ThemesTab) self.gridLayout_3.setObjectName("gridLayout_3") self.horizontalLayout_5 = QtWidgets.QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.mColorButton = QgsColorButton(self.ThemesTab) self.mColorButton.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton.setAcceptDrops(False) self.mColorButton.setColor(QtGui.QColor(0, 255, 0)) self.mColorButton.setShowMenu(False) self.mColorButton.setProperty("acceptLiveUpdates", False) self.mColorButton.setObjectName("mColorButton") self.horizontalLayout_5.addWidget(self.mColorButton) self.checkBoxData = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxData.setTristate(True) self.checkBoxData.setObjectName("checkBoxData") self.horizontalLayout_5.addWidget(self.checkBoxData) self.gridLayout_3.addLayout(self.horizontalLayout_5, 0, 0, 1, 1) self.refreshButton = QtWidgets.QPushButton(self.ThemesTab) self.refreshButton.setObjectName("refreshButton") self.gridLayout_3.addWidget(self.refreshButton, 0, 1, 2, 1) self.horizontalLayout_6 = QtWidgets.QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.mColorButton_2 = QgsColorButton(self.ThemesTab) self.mColorButton_2.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_2.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_2.setAcceptDrops(False) self.mColorButton_2.setColor(QtGui.QColor(255, 215, 80)) self.mColorButton_2.setShowMenu(False) self.mColorButton_2.setProperty("acceptLiveUpdates", False) self.mColorButton_2.setObjectName("mColorButton_2") self.horizontalLayout_6.addWidget(self.mColorButton_2) self.checkBoxGas_low = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxGas_low.setTristate(True) self.checkBoxGas_low.setObjectName("checkBoxGas_low") self.horizontalLayout_6.addWidget(self.checkBoxGas_low) self.gridLayout_3.addLayout(self.horizontalLayout_6, 1, 0, 1, 1) self.horizontalLayout_7 = QtWidgets.QHBoxLayout() self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.mColorButton_3 = QgsColorButton(self.ThemesTab) self.mColorButton_3.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_3.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_3.setAcceptDrops(False) self.mColorButton_3.setColor(QtGui.QColor(255, 175, 60)) self.mColorButton_3.setShowMenu(False) self.mColorButton_3.setProperty("acceptLiveUpdates", False) self.mColorButton_3.setObjectName("mColorButton_3") self.horizontalLayout_7.addWidget(self.mColorButton_3) self.checkBoxGas_high = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxGas_high.setTristate(True) self.checkBoxGas_high.setObjectName("checkBoxGas_high") self.horizontalLayout_7.addWidget(self.checkBoxGas_high) self.gridLayout_3.addLayout(self.horizontalLayout_7, 2, 0, 1, 1) self.horizontalLayout_8 = QtWidgets.QHBoxLayout() self.horizontalLayout_8.setObjectName("horizontalLayout_8") self.mColorButton_4 = QgsColorButton(self.ThemesTab) self.mColorButton_4.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_4.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_4.setAcceptDrops(False) self.mColorButton_4.setColor(QtGui.QColor(255, 127, 0)) self.mColorButton_4.setShowMenu(False) self.mColorButton_4.setProperty("acceptLiveUpdates", False) self.mColorButton_4.setObjectName("mColorButton_4") self.horizontalLayout_8.addWidget(self.mColorButton_4) self.checkBoxDanger = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxDanger.setTristate(True) self.checkBoxDanger.setObjectName("checkBoxDanger") self.horizontalLayout_8.addWidget(self.checkBoxDanger) self.gridLayout_3.addLayout(self.horizontalLayout_8, 3, 0, 1, 2) self.horizontalLayout_20 = QtWidgets.QHBoxLayout() self.horizontalLayout_20.setObjectName("horizontalLayout_20") self.mColorButton_8 = QgsColorButton(self.ThemesTab) self.mColorButton_8.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_8.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_8.setAcceptDrops(False) self.mColorButton_8.setColor(QtGui.QColor(255, 0, 0)) self.mColorButton_8.setShowMenu(False) self.mColorButton_8.setProperty("acceptLiveUpdates", False) self.mColorButton_8.setObjectName("mColorButton_8") self.horizontalLayout_20.addWidget(self.mColorButton_8) self.checkBoxElec_land = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxElec_land.setTristate(True) self.checkBoxElec_land.setObjectName("checkBoxElec_land") self.horizontalLayout_20.addWidget(self.checkBoxElec_land) self.gridLayout_3.addLayout(self.horizontalLayout_20, 4, 0, 1, 2) self.horizontalLayout_11 = QtWidgets.QHBoxLayout() self.horizontalLayout_11.setObjectName("horizontalLayout_11") self.mColorButton_7 = QgsColorButton(self.ThemesTab) self.mColorButton_7.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_7.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_7.setAcceptDrops(False) self.mColorButton_7.setColor(QtGui.QColor(255, 0, 0)) self.mColorButton_7.setShowMenu(False) self.mColorButton_7.setProperty("acceptLiveUpdates", False) self.mColorButton_7.setObjectName("mColorButton_7") self.horizontalLayout_11.addWidget(self.mColorButton_7) self.checkBoxElec_high = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxElec_high.setTristate(True) self.checkBoxElec_high.setObjectName("checkBoxElec_high") self.horizontalLayout_11.addWidget(self.checkBoxElec_high) self.gridLayout_3.addLayout(self.horizontalLayout_11, 5, 0, 1, 1) self.horizontalLayout_10 = QtWidgets.QHBoxLayout() self.horizontalLayout_10.setObjectName("horizontalLayout_10") self.mColorButton_6 = QgsColorButton(self.ThemesTab) self.mColorButton_6.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_6.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_6.setAcceptDrops(False) self.mColorButton_6.setColor(QtGui.QColor(200, 0, 0)) self.mColorButton_6.setShowMenu(False) self.mColorButton_6.setProperty("acceptLiveUpdates", False) self.mColorButton_6.setObjectName("mColorButton_6") self.horizontalLayout_10.addWidget(self.mColorButton_6) self.checkBoxElec_mid = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxElec_mid.setTristate(True) self.checkBoxElec_mid.setObjectName("checkBoxElec_mid") self.horizontalLayout_10.addWidget(self.checkBoxElec_mid) self.gridLayout_3.addLayout(self.horizontalLayout_10, 6, 0, 1, 2) self.horizontalLayout_9 = QtWidgets.QHBoxLayout() self.horizontalLayout_9.setObjectName("horizontalLayout_9") self.mColorButton_5 = QgsColorButton(self.ThemesTab) self.mColorButton_5.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_5.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_5.setAcceptDrops(False) self.mColorButton_5.setColor(QtGui.QColor(150, 0, 0)) self.mColorButton_5.setShowMenu(False) self.mColorButton_5.setObjectName("mColorButton_5") self.horizontalLayout_9.addWidget(self.mColorButton_5) self.checkBoxElec_low = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxElec_low.setTristate(True) self.checkBoxElec_low.setObjectName("checkBoxElec_low") self.horizontalLayout_9.addWidget(self.checkBoxElec_low) self.gridLayout_3.addLayout(self.horizontalLayout_9, 7, 0, 1, 1) self.horizontalLayout_16 = QtWidgets.QHBoxLayout() self.horizontalLayout_16.setObjectName("horizontalLayout_16") self.mColorButton_13 = QgsColorButton(self.ThemesTab) self.mColorButton_13.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_13.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_13.setAcceptDrops(False) self.mColorButton_13.setColor(QtGui.QColor(182, 74, 0)) self.mColorButton_13.setShowMenu(False) self.mColorButton_13.setProperty("acceptLiveUpdates", False) self.mColorButton_13.setObjectName("mColorButton_13") self.horizontalLayout_16.addWidget(self.mColorButton_13) self.checkBoxChemical = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxChemical.setTristate(True) self.checkBoxChemical.setObjectName("checkBoxChemical") self.horizontalLayout_16.addWidget(self.checkBoxChemical) self.gridLayout_3.addLayout(self.horizontalLayout_16, 8, 0, 1, 1) self.vectorCheckBox = QtWidgets.QCheckBox(self.ThemesTab) self.vectorCheckBox.setObjectName("vectorCheckBox") self.gridLayout_3.addWidget(self.vectorCheckBox, 8, 1, 1, 1) self.horizontalLayout_12 = QtWidgets.QHBoxLayout() self.horizontalLayout_12.setObjectName("horizontalLayout_12") self.mColorButton_9 = QgsColorButton(self.ThemesTab) self.mColorButton_9.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_9.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_9.setAcceptDrops(False) self.mColorButton_9.setColor(QtGui.QColor(186, 56, 168)) self.mColorButton_9.setShowMenu(False) self.mColorButton_9.setObjectName("mColorButton_9") self.horizontalLayout_12.addWidget(self.mColorButton_9) self.checkBoxSewer_free = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxSewer_free.setTristate(True) self.checkBoxSewer_free.setObjectName("checkBoxSewer_free") self.horizontalLayout_12.addWidget(self.checkBoxSewer_free) self.gridLayout_3.addLayout(self.horizontalLayout_12, 9, 0, 1, 1) self.rasterCheckBox = QtWidgets.QCheckBox(self.ThemesTab) self.rasterCheckBox.setEnabled(True) self.rasterCheckBox.setObjectName("rasterCheckBox") self.gridLayout_3.addWidget(self.rasterCheckBox, 9, 1, 1, 1) self.horizontalLayout_13 = QtWidgets.QHBoxLayout() self.horizontalLayout_13.setObjectName("horizontalLayout_13") self.mColorButton_10 = QgsColorButton(self.ThemesTab) self.mColorButton_10.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_10.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_10.setAcceptDrops(False) self.mColorButton_10.setColor(QtGui.QColor(128, 0, 128)) self.mColorButton_10.setShowMenu(False) self.mColorButton_10.setProperty("acceptLiveUpdates", False) self.mColorButton_10.setObjectName("mColorButton_10") self.horizontalLayout_13.addWidget(self.mColorButton_10) self.checkBoxSewer_pressure = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxSewer_pressure.setTristate(True) self.checkBoxSewer_pressure.setObjectName("checkBoxSewer_pressure") self.horizontalLayout_13.addWidget(self.checkBoxSewer_pressure) self.gridLayout_3.addLayout(self.horizontalLayout_13, 10, 0, 1, 1) self.horizontalLayout_14 = QtWidgets.QHBoxLayout() self.horizontalLayout_14.setObjectName("horizontalLayout_14") self.mColorButton_11 = QgsColorButton(self.ThemesTab) self.mColorButton_11.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_11.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_11.setAcceptDrops(False) self.mColorButton_11.setColor(QtGui.QColor(0, 128, 128)) self.mColorButton_11.setShowMenu(False) self.mColorButton_11.setObjectName("mColorButton_11") self.horizontalLayout_14.addWidget(self.mColorButton_11) self.checkBoxHeat = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxHeat.setTristate(True) self.checkBoxHeat.setObjectName("checkBoxHeat") self.horizontalLayout_14.addWidget(self.checkBoxHeat) self.gridLayout_3.addLayout(self.horizontalLayout_14, 11, 0, 1, 1) self.annotationCheckBox = QtWidgets.QCheckBox(self.ThemesTab) self.annotationCheckBox.setTristate(True) self.annotationCheckBox.setObjectName("annotationCheckBox") self.gridLayout_3.addWidget(self.annotationCheckBox, 11, 1, 1, 1) self.horizontalLayout_15 = QtWidgets.QHBoxLayout() self.horizontalLayout_15.setObjectName("horizontalLayout_15") self.mColorButton_12 = QgsColorButton(self.ThemesTab) self.mColorButton_12.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_12.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_12.setAcceptDrops(False) self.mColorButton_12.setColor(QtGui.QColor(0, 0, 255)) self.mColorButton_12.setShowMenu(False) self.mColorButton_12.setObjectName("mColorButton_12") self.horizontalLayout_15.addWidget(self.mColorButton_12) self.checkBoxWater = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxWater.setTristate(True) self.checkBoxWater.setObjectName("checkBoxWater") self.horizontalLayout_15.addWidget(self.checkBoxWater) self.gridLayout_3.addLayout(self.horizontalLayout_15, 12, 0, 1, 1) self.dimensioningCheckBox = QtWidgets.QCheckBox(self.ThemesTab) self.dimensioningCheckBox.setTristate(True) self.dimensioningCheckBox.setObjectName("dimensioningCheckBox") self.gridLayout_3.addWidget(self.dimensioningCheckBox, 12, 1, 1, 1) self.horizontalLayout_17 = QtWidgets.QHBoxLayout() self.horizontalLayout_17.setObjectName("horizontalLayout_17") self.mColorButton_14 = QgsColorButton(self.ThemesTab) self.mColorButton_14.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_14.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_14.setAcceptDrops(False) self.mColorButton_14.setColor(QtGui.QColor(145, 138, 111)) self.mColorButton_14.setShowMenu(False) self.mColorButton_14.setObjectName("mColorButton_14") self.horizontalLayout_17.addWidget(self.mColorButton_14) self.checkBoxOrphan = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxOrphan.setTristate(True) self.checkBoxOrphan.setObjectName("checkBoxOrphan") self.horizontalLayout_17.addWidget(self.checkBoxOrphan) self.gridLayout_3.addLayout(self.horizontalLayout_17, 13, 0, 1, 1) self.locationCheckBox = QtWidgets.QCheckBox(self.ThemesTab) self.locationCheckBox.setTristate(True) self.locationCheckBox.setObjectName("locationCheckBox") self.gridLayout_3.addWidget(self.locationCheckBox, 13, 1, 1, 1) self.horizontalLayout_18 = QtWidgets.QHBoxLayout() self.horizontalLayout_18.setObjectName("horizontalLayout_18") self.mColorButton_15 = QgsColorButton(self.ThemesTab) self.mColorButton_15.setMinimumSize(QtCore.QSize(40, 10)) self.mColorButton_15.setMaximumSize(QtCore.QSize(40, 10)) self.mColorButton_15.setAcceptDrops(False) self.mColorButton_15.setColor(QtGui.QColor(111, 92, 16)) self.mColorButton_15.setShowMenu(False) self.mColorButton_15.setObjectName("mColorButton_15") self.horizontalLayout_18.addWidget(self.mColorButton_15) self.checkBoxOther = QtWidgets.QCheckBox(self.ThemesTab) self.checkBoxOther.setTristate(True) self.checkBoxOther.setObjectName("checkBoxOther") self.horizontalLayout_18.addWidget(self.checkBoxOther) self.gridLayout_3.addLayout(self.horizontalLayout_18, 14, 0, 1, 1) self.topoCheckBox = QtWidgets.QCheckBox(self.ThemesTab) self.topoCheckBox.setTristate(True) self.topoCheckBox.setObjectName("topoCheckBox") self.gridLayout_3.addWidget(self.topoCheckBox, 14, 1, 1, 1) self.tabWidget.addTab(self.ThemesTab, "") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tab) self.verticalLayout_3.setObjectName("verticalLayout_3") self.groupBox = QtWidgets.QGroupBox(self.tab) self.groupBox.setObjectName("groupBox") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.groupBox) self.verticalLayout_2.setObjectName("verticalLayout_2") self.horizontalLayout_19 = QtWidgets.QHBoxLayout() self.horizontalLayout_19.setObjectName("horizontalLayout_19") self.optionMsgDirButton = QtWidgets.QPushButton(self.groupBox) self.optionMsgDirButton.setMinimumSize(QtCore.QSize(0, 0)) self.optionMsgDirButton.setObjectName("optionMsgDirButton") self.horizontalLayout_19.addWidget(self.optionMsgDirButton) spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_19.addItem(spacerItem5) self.verticalLayout_2.addLayout(self.horizontalLayout_19) self.textEditDirPreffered = QtWidgets.QTextEdit(self.groupBox) self.textEditDirPreffered.setMinimumSize(QtCore.QSize(20, 20)) self.textEditDirPreffered.setMaximumSize(QtCore.QSize(1000, 100)) self.textEditDirPreffered.setBaseSize(QtCore.QSize(200, 40)) self.textEditDirPreffered.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.textEditDirPreffered.setLineWrapMode(QtWidgets.QTextEdit.NoWrap) self.textEditDirPreffered.setReadOnly(True) self.textEditDirPreffered.setObjectName("textEditDirPreffered") self.verticalLayout_2.addWidget(self.textEditDirPreffered) self.verticalLayout_3.addWidget(self.groupBox) spacerItem6 = QtWidgets.QSpacerItem(20, 318, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout_3.addItem(spacerItem6) self.tabWidget.addTab(self.tab, "") self.verticalLayout.addWidget(self.tabWidget) self.retranslateUi(B4UdigNL) self.tabWidget.setCurrentIndex(1) QtCore.QMetaObject.connectSlotsByName(B4UdigNL) def retranslateUi(self, B4UdigNL): _translate = QtCore.QCoreApplication.translate B4UdigNL.setWindowTitle(_translate("B4UdigNL", "KLIC Viewer")) self.messageBox.setTitle(_translate("B4UdigNL", "KLIC Berichten")) self.openMsgButton.setText(_translate("B4UdigNL", "&Open Folder...")) self.openArchiveButton.setText(_translate("B4UdigNL", "Open &Zip-bestand...")) self.gotoButton.setText(_translate("B4UdigNL", "&Ga naar")) self.bestScaleButton.setText(_translate("B4UdigNL", "Beste S&chaal")) self.removeMsgButton.setText(_translate("B4UdigNL", "&Sluit Bericht")) self.additionsBox.setTitle(_translate("B4UdigNL", "Bijlagen")) self.openDocButton.setText(_translate("B4UdigNL", "Open &Bijlage(n)")) self.saveButton.setText(_translate("B4UdigNL", "Opslaan in Project")) self.helpButton.setText(_translate("B4UdigNL", "&Help...")) self.closeButton.setText(_translate("B4UdigNL", "Afsl&uiten")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.messageTab), _translate("B4UdigNL", "Berichten")) self.checkBoxData.setText(_translate("B4UdigNL", "Datatransport")) self.refreshButton.setText(_translate("B4UdigNL", "&Ververs")) self.checkBoxGas_low.setText(_translate("B4UdigNL", "Gas lage druk")) self.checkBoxGas_high.setText(_translate("B4UdigNL", "Gas hoge druk")) self.checkBoxDanger.setText(_translate("B4UdigNL", "Buisleiding gevaarlijke inhoud")) self.checkBoxElec_land.setText(_translate("B4UdigNL", "Electriciteit landelijk hoogspanningsnet")) self.checkBoxElec_high.setText(_translate("B4UdigNL", "Electriciteit hoogspanning")) self.checkBoxElec_mid.setText(_translate("B4UdigNL", "Electriciteit middenspanning")) self.checkBoxElec_low.setText(_translate("B4UdigNL", "Electriciteit laagspanning")) self.checkBoxChemical.setText(_translate("B4UdigNL", "(Petro) chemie")) self.vectorCheckBox.setText(_translate("B4UdigNL", "Vector")) self.checkBoxSewer_free.setText(_translate("B4UdigNL", "Riool vrij verval")) self.rasterCheckBox.setText(_translate("B4UdigNL", "Raster")) self.checkBoxSewer_pressure.setText(_translate("B4UdigNL", "Riool onder druk")) self.checkBoxHeat.setText(_translate("B4UdigNL", "Warmte")) self.annotationCheckBox.setText(_translate("B4UdigNL", "Annotatie")) self.checkBoxWater.setText(_translate("B4UdigNL", "Water ")) self.dimensioningCheckBox.setText(_translate("B4UdigNL", "Maatvoering")) self.checkBoxOrphan.setText(_translate("B4UdigNL", "Wees")) self.locationCheckBox.setText(_translate("B4UdigNL", "Ligging")) self.checkBoxOther.setText(_translate("B4UdigNL", "Overig")) self.topoCheckBox.setText(_translate("B4UdigNL", "Topo")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.ThemesTab), _translate("B4UdigNL", "Thema\'s")) self.groupBox.setTitle(_translate("B4UdigNL", "KLIC Berichten")) self.optionMsgDirButton.setText(_translate("B4UdigNL", "Standaard folder...")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("B4UdigNL", "Opties"))
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 Serval(object): def __init__(self, iface): self.iface = iface self.canvas = self.iface.mapCanvas() self.plugin_dir = os.path.dirname(__file__) self.uc = UserCommunication(iface, 'Serval') self.mode = 'probe' self.bands = None self.raster = None self.px, self.py = [0, 0] self.last_point = QgsPointXY(0, 0) self.undos = defaultdict(list) self.redos = defaultdict(list) self.qgis_project = QgsProject() self.menu = u'Serval' self.actions = [] self.toolbar = self.iface.addToolBar(u'Serval') self.toolbar.setObjectName(u'Serval') # Map tools self.probeTool = QgsMapToolEmitPoint(self.canvas) self.probeTool.setObjectName('ServalProbeTool') self.probeTool.setCursor( QCursor(QPixmap(icon_path('probe_tool.svg')), hotX=2, hotY=22)) self.probeTool.canvasClicked.connect(self.point_clicked) self.drawTool = QgsMapToolEmitPoint(self.canvas) self.drawTool.setObjectName('ServalDrawTool') self.drawTool.setCursor( QCursor(QPixmap(icon_path('draw_tool.svg')), hotX=2, hotY=22)) self.drawTool.canvasClicked.connect(self.point_clicked) self.gomTool = QgsMapToolEmitPoint(self.canvas) self.gomTool.setObjectName('ServalGomTool') self.gomTool.setCursor( QCursor(QPixmap(icon_path('gom_tool.svg')), hotX=5, hotY=19)) self.gomTool.canvasClicked.connect(self.point_clicked) self.mColorButton = QgsColorButton() icon1 = QIcon(icon_path('mIconColorBox.svg')) self.mColorButton.setIcon(icon1) self.mColorButton.setMinimumSize(QSize(40, 24)) self.mColorButton.setMaximumSize(QSize(40, 24)) self.mColorButton.colorChanged.connect(self.set_rgb_from_picker) self.b1SBox = BandSpinBox() self.b2SBox = BandSpinBox() self.b3SBox = BandSpinBox() self.sboxes = [self.b1SBox, self.b2SBox, self.b3SBox] for sb in self.sboxes: sb.user_hit_enter.connect(self.change_cell_value_key) self.iface.currentLayerChanged.connect(self.set_active_raster) self.qgis_project.layersAdded.connect(self.set_active_raster) self.canvas.mapToolSet.connect(self.check_active_tool) def initGui(self): # Menu and toolbar actions self.add_action('serval_icon.svg', text=u'Show Serval Toolbar', add_to_menu=True, add_to_toolbar=False, callback=self.show_toolbar, parent=self.iface.mainWindow()) self.probe_btn = self.add_action('probe.svg', text=u'Probing Mode', whats_this=u'Probing Mode', add_to_toolbar=True, callback=self.activate_probing, parent=self.iface.mainWindow()) self.draw_btn = self.add_action('draw.svg', text=u'Drawing Mode', whats_this=u'Drawing Mode', add_to_toolbar=True, callback=self.activate_drawing, parent=self.iface.mainWindow()) self.gom_btn = self.add_action( 'gom.svg', text=u'Set Raster Cell Value to NoData', whats_this=u'Set Raster Cell Value to NoData', add_to_toolbar=True, callback=self.activate_gom, parent=self.iface.mainWindow()) self.checkable_tool_btns = [ self.draw_btn, self.probe_btn, self.gom_btn ] self.def_nodata_btn = self.add_action( 'define_nodata.svg', text=u'Define/Change Raster NoData Value', whats_this=u'Define/Change Raster NoData Value', add_to_toolbar=True, callback=self.define_nodata, parent=self.iface.mainWindow()) self.toolbar.addWidget(self.mColorButton) self.setup_spin_boxes() self.undo_btn = self.add_action('undo.svg', text=u'Undo', whats_this=u'Undo', add_to_toolbar=True, callback=self.undo, parent=self.iface.mainWindow()) self.redo_btn = self.add_action('redo.svg', text=u'Redo', whats_this=u'Redo', add_to_toolbar=True, callback=self.redo, parent=self.iface.mainWindow()) self.show_help = self.add_action('help.svg', text=u'Help', whats_this=u'Help', add_to_toolbar=True, add_to_menu=True, callback=self.show_website, parent=self.iface.mainWindow()) self.set_active_raster() self.check_undo_redo_btns() def add_action(self, icon_name, text, callback, enabled_flag=True, add_to_menu=False, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): icon = QIcon(icon_path(icon_name)) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def unload(self): self.iface.actionPan().trigger() for action in self.actions: self.iface.removePluginMenu(u'Serval', action) self.iface.removeToolBarIcon(action) del self.toolbar def show_toolbar(self): if self.toolbar: self.toolbar.show() def check_active_tool(self, tool): try: if not tool.objectName() in [ 'ServalDrawTool', 'ServalProbeTool', 'ServalGomTool' ]: self.probe_btn.setChecked(False) self.draw_btn.setChecked(False) self.gom_btn.setChecked(False) except AttributeError: pass def set_checked_tool_btn(self, cur_tool_btn): for btn in self.checkable_tool_btns: if btn == cur_tool_btn: btn.setChecked(True) else: btn.setChecked(False) def activate_probing(self): self.mode = 'probe' self.canvas.setMapTool(self.probeTool) self.set_checked_tool_btn(self.probe_btn) def activate_drawing(self): self.mode = 'draw' self.canvas.setMapTool(self.drawTool) self.set_checked_tool_btn(self.draw_btn) def activate_gom(self): self.mode = 'gom' self.canvas.setMapTool(self.gomTool) self.set_checked_tool_btn(self.gom_btn) def setup_spin_boxes(self): for sbox in self.sboxes: sbox.setMinimumSize(QSize(60, 25)) sbox.setMaximumSize(QSize(60, 25)) sbox.setAlignment(Qt.AlignLeft) sbox.setButtonSymbols(QAbstractSpinBox.NoButtons) sbox.setKeyboardTracking(False) sbox.setShowClearButton(False) sbox.setExpressionsEnabled(False) sbox.setStyleSheet("") self.toolbar.addWidget(sbox) def point_clicked(self, point=None, button=None): # check if active layer is raster if self.raster is None: self.uc.bar_warn("Choose a raster to work with...", dur=3) return # check if coordinates trasformation is required canvas_srs = self.iface.mapCanvas().mapSettings().destinationCrs() if point is None: pos = self.last_point elif not canvas_srs == self.raster.crs(): project = QgsProject.instance() srs_transform = QgsCoordinateTransform(canvas_srs, self.raster.crs(), project) try: pos = srs_transform.transform(point) except QgsCsException as err: self.uc.bar_warn( "Point coordinates transformation failed! Check the raster projection:\n\n{}" .format(repr(err)), dur=5) return else: pos = QgsPointXY(point.x(), point.y()) # keep last clicked point self.last_point = pos # check if the point is within active raster bounds if self.rbounds[0] <= pos.x() <= self.rbounds[2]: self.px = int((pos.x() - self.rbounds[0]) / self.raster.rasterUnitsPerPixelX() ) # - self.gt[0]) / self.gt[1]) else: self.uc.bar_info("Out of x bounds", dur=2) return if self.rbounds[1] <= pos.y() <= self.rbounds[3]: self.py = int((self.rbounds[3] - pos.y()) / self.raster.rasterUnitsPerPixelY() ) # - self.gt[3]) / self.gt[5]) else: self.uc.bar_info("Out of y bounds", dur=2) return # probe current raster value, dict: band_nr -> value vals = self.rdp.identify(pos, QgsRaster.IdentifyFormatValue).results() # for rasters having more that 3 bands, ignore other than 1-3 bands_to_ignore = [i for i in vals.keys() if i > 3] for band_nr in bands_to_ignore: del vals[band_nr] # data types for each band dtypes = [] for nr in range(1, min(4, self.band_count + 1)): # bands data type dtypes.append(self.bands[nr]['qtype']) # check if nodata is defined if self.mode == 'gom' and self.bands[nr]['nodata'] is None: msg = 'NODATA value is not defined for one of the raster\'s bands.\n' msg += 'Please define it in raster properties dialog!' self.uc.show_warn(msg) return # if in probing mode, set band's spinbox value if self.mode == 'probe': val = vals[nr] if is_number( vals[nr]) else self.bands[nr]['nodata'] self.bands[nr]['sbox'].setValue(val) self.bands[nr]['sbox'].setFocus() self.bands[nr]['sbox'].selectAll() if not self.mode == 'probe': old_vals = [ v if v is not None else self.bands[k]['nodata'] for k, v in sorted(vals.items()) ] if self.mode == 'gom': temp_vals = [ self.bands[nr]['nodata'] for nr in sorted(vals.keys()) ] new_vals = [ int(v) if dtypes[i] < 6 else float(v) for i, v in enumerate(temp_vals) ] else: temp_vals = [ self.bands[nr]['sbox'].value() for nr in sorted(vals.keys()) ] new_vals = [ int(v) if dtypes[i] < 6 else float(v) for i, v in enumerate(temp_vals) ] # store all bands' changes to undo list self.undos[self.raster.id()].append( [old_vals, new_vals, self.px, self.py, pos]) # write the new cell value(s) self.change_cell_value(new_vals) if self.band_count > 2: self.mColorButton.setColor( QColor(self.bands[1]['sbox'].value(), self.bands[2]['sbox'].value(), self.bands[3]['sbox'].value())) def set_rgb_from_picker(self, c): """Set bands spinboxes values after color change in the color picker""" self.bands[1]['sbox'].setValue(c.red()) self.bands[2]['sbox'].setValue(c.green()) self.bands[3]['sbox'].setValue(c.blue()) def change_cell_value(self, vals, x=None, y=None): """Save new bands values to data provider""" if not self.rdp.isEditable(): success = self.rdp.setEditable(True) if not success: self.uc.show_warn('QGIS can\'t modify this type of raster') return if not x: x = self.px y = self.py for nr in range(1, min(4, self.band_count + 1)): rblock = QgsRasterBlock(self.bands[nr]['qtype'], 1, 1) rblock.setValue(0, 0, vals[nr - 1]) success = self.rdp.writeBlock(rblock, nr, x, y) if not success: self.uc.show_warn('QGIS can\'t modify this type of raster') return self.rdp.setEditable(False) self.raster.triggerRepaint() # prepare raster for next actions self.prepare_raster(True) self.check_undo_redo_btns() def change_cell_value_key(self): """Change cell value after user changes band's spinbox value and hits Enter key""" if self.last_point: pm = self.mode self.mode = 'draw' self.point_clicked() self.mode = pm def undo(self): if self.undos[self.raster.id()]: data = self.undos[self.raster.id()].pop() self.redos[self.raster.id()].append(data) else: return self.change_cell_value(data[0], data[2], data[3]) def redo(self): if self.redos[self.raster.id()]: data = self.redos[self.raster.id()].pop() self.undos[self.raster.id()].append(data) else: return self.change_cell_value(data[1], data[2], data[3]) def define_nodata(self): """Define and write a new NoData value to raster file""" if not self.raster: self.uc.bar_warn( 'Select a raster layer to define/change NoData value!') return # check if user defined additional NODATA value if self.rdp.userNoDataValues(1): note = '\nNote: there is a user defined NODATA value.\nCheck the raster properties (Transparency).' else: note = '' # first band data type dt = self.rdp.dataType(1) # current NODATA value if self.rdp.sourceHasNoDataValue(1): cur_nodata = self.rdp.sourceNoDataValue(1) if dt < 6: cur_nodata = '{0:d}'.format(int(float(cur_nodata))) else: cur_nodata = '' label = 'Define/change raster NODATA value.\n\n' label += 'Raster data type: {}.{}'.format(dtypes[dt]['name'], note) nd, ok = QInputDialog.getText(None, "Define NODATA Value", label, QLineEdit.Normal, str(cur_nodata)) if not ok: return if not is_number(nd): self.uc.show_warn('Wrong NODATA value!') return new_nodata = int(nd) if dt < 6 else float(nd) # set the NODATA value for each band res = [] for nr in range(1, min(4, self.band_count + 1)): res.append(self.rdp.setNoDataValue(nr, new_nodata)) self.rdp.sourceHasNoDataValue(nr) if False in res: self.uc.show_warn('Setting new NODATA value failed!') else: self.uc.bar_info('Succesful setting new NODATA values!', dur=2) self.prepare_raster() self.raster.triggerRepaint() def check_undo_redo_btns(self): """Enable/Disable undo and redo buttons based on availability of undo/redo steps""" try: if len(self.undos[self.raster.id()]) == 0: self.undo_btn.setDisabled(True) else: self.undo_btn.setEnabled(True) except: self.undo_btn.setDisabled(True) try: if len(self.redos[self.raster.id()]) == 0: self.redo_btn.setDisabled(True) else: self.redo_btn.setEnabled(True) except: self.redo_btn.setDisabled(True) def disable_toolbar_actions(self): # disable all toolbar actions but Help (for vectors and unsupported rasters) for action in self.actions: action.setDisabled(True) self.show_help.setEnabled(True) def check_layer(self, layer): """Check if we can work with the raster""" if layer == None \ or not layer.isValid() \ or not layer.type() == raster_layer_type \ or not (layer.dataProvider().capabilities() & QgsRasterDataProvider.Create) \ or layer.crs() is None: return False else: return True def set_active_raster(self): """Active layer has change - check if it is a raster layer and prepare it for the plugin""" if self.bands: self.bands = None for sbox in self.sboxes: sbox.setValue(0) layer = self.iface.activeLayer() if self.check_layer(layer): self.raster = layer self.rdp = layer.dataProvider() self.band_count = layer.bandCount() # is data type supported? supported = True for nr in range(1, min(4, self.band_count + 1)): if self.rdp.dataType(nr) == 0 or self.rdp.dataType(nr) > 7: t = dtypes[self.rdp.dataType(nr)]['name'] supported = False if supported: # enable all toolbar actions for action in self.actions: action.setEnabled(True) # if raster properties change, get them (refeshes view) self.raster.rendererChanged.connect(self.prepare_raster) self.prepare_raster(supported) # not supported data type else: msg = 'The raster data type is: {}.'.format(t) msg += '\nServal can\'t work with it, sorry!' self.uc.show_warn(msg) self.reset_raster() # it is not a supported raster layer else: self.reset_raster() self.check_undo_redo_btns() def reset_raster(self): self.raster = None self.mColorButton.setDisabled(True) self.prepare_raster(False) def prepare_raster(self, supported=True): """Open raster using GDAL if it is supported""" # reset bands' spin boxes for i, sbox in enumerate(self.sboxes): sbox.setProperty('bandNr', i + 1) sbox.setDisabled(True) if not supported: return if self.band_count > 2: self.mColorButton.setEnabled(True) else: self.mColorButton.setDisabled(True) extent = self.raster.extent() self.rbounds = extent.toRectF().getCoords() self.bands = {} for nr in range(1, min(4, self.band_count + 1)): self.bands[nr] = {} self.bands[nr]['sbox'] = self.sboxes[nr - 1] # NODATA if self.rdp.sourceHasNoDataValue(nr): # source nodata value? self.bands[nr]['nodata'] = self.rdp.sourceNoDataValue(nr) # use the src nodata self.rdp.setUseSourceNoDataValue(nr, True) # no nodata defined in the raster source else: # check if user defined any nodata values if self.rdp.userNoDataValues(nr): # get min nodata value from the first user nodata range nd_ranges = self.rdp.userNoDataValues(nr) self.bands[nr]['nodata'] = nd_ranges[0].min() else: # leave nodata undefined self.bands[nr]['nodata'] = None # enable band's spin box self.bands[nr]['sbox'].setEnabled(True) # get bands data type dt = self.bands[nr]['qtype'] = self.rdp.dataType(nr) # set spin boxes properties self.bands[nr]['sbox'].setMinimum(dtypes[dt]['min']) self.bands[nr]['sbox'].setMaximum(dtypes[dt]['max']) self.bands[nr]['sbox'].setDecimals(dtypes[dt]['dig']) @staticmethod def show_website(): QDesktopServices.openUrl(QUrl('https://github.com/erpas/serval/wiki'))
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 SaveFigureDlg(QDialog): def __init__(self, dFigureParams, parent=None): super(SaveFigureDlg, self).__init__(parent) self.dFigureParams = dFigureParams layout = QVBoxLayout() # output format settings grpFormatSettings = QGroupBox("Output format") lytFormatSettings = QGridLayout() # format lytFormatSettings.addWidget(QLabel("File format"), 0, 0, 1, 1) self.cmbFileFormat = QComboBox() self.cmbFileFormat.insertItems(0, ltFileFormats) sFileFormat = self.dPlotStyles["file_format"] iCurrFileFrmtNdx = ltFileFormats.index(sFileFormat) if sFileFormat in ltFileFormats else 0 self.cmbFileFormat.setCurrentIndex(iCurrFileFrmtNdx) lytFormatSettings.addWidget(self.cmbFileFormat, 0, 1, 1, 1) # dpi (for rasters) lytFormatSettings.addWidget(QLabel("Dpi (for rasters"), 1, 0, 1, 1) self.cmbDpiResolution = QComboBox() self.cmbDpiResolution.insertItems(0, liDpiResolutions) iCurrDpiResolution = self.dPlotStyles["dpi_resolution"] iCurrDpiResolNdx = ltFileFormats.index(iCurrDpiResolution) if iCurrDpiResolution in ltFileFormats else 0 self.cmbDpiResolution.setCurrentIndex(iCurrDpiResolNdx) lytFormatSettings.addWidget(self.cmbDpiResolution, 1, 1, 1, 1) # set/add to layout grpFormatSettings.setLayout(lytFormatSettings) layout.addWidget(grpFormatSettings) # output file path grpPoles = QGroupBox("Poles") lytPoles = QGridLayout() # marker color lytPoles.addWidget(QLabel("Marker color"), 0, 0, 1, 1) self.btnPointColor = QgsColorButton() point_color = self.dPlotStyles["marker_color"] self.btnPointColor.setColor(QColor(point_color)) lytPoles.addWidget(self.btnPointColor, 0, 1, 1, 1) # marker style lytPoles.addWidget(QLabel("Marker style"), 0, 2, 1, 1) self.cmbPointStyle = QComboBox() self.cmbPointStyle.insertItems(0, list(ltMarkerStyles.keys())) point_style = self.dPlotStyles["marker_style"] point_style_ndx = list(ltMarkerStyles.keys()).index(point_style) if point_style in list(ltMarkerStyles.keys()) else 0 self.cmbPointStyle.setCurrentIndex(point_style_ndx) lytPoles.addWidget(self.cmbPointStyle, 0, 3, 1, 1) # marker size lytPoles.addWidget(QLabel("Marker size"), 1, 0, 1, 1) lnPointSizes = [2, 4, 6, 8, 10, 15, 20] self.cmbPointSize = QComboBox() ltPointSizeVals = [str(val) + " pt(s)" for val in lnPointSizes] self.cmbPointSize.insertItems(0, ltPointSizeVals) point_size = self.dPlotStyles["marker_size"] point_style_ndx = ltPointSizeVals.index(point_size) if point_size in ltPointSizeVals else 2 self.cmbPointSize.setCurrentIndex(point_style_ndx) lytPoles.addWidget(self.cmbPointSize, 1, 1, 1, 1) # marker transparency lytPoles.addWidget(QLabel("Marker transp."), 1, 2, 1, 1) lnPointTransparencies = [0, 25, 50, 75] self.cmbPointTransp = QComboBox() ltPointTranspPrcntVals = [str(val) + "%" for val in lnPointTransparencies] self.cmbPointTransp.insertItems(0, ltPointTranspPrcntVals) point_transp = self.dPlotStyles["marker_transp"] point_transp_ndx = ltPointTranspPrcntVals.index(point_transp) if point_transp in ltPointTranspPrcntVals else 0 self.cmbPointTransp.setCurrentIndex(point_transp_ndx) lytPoles.addWidget(self.cmbPointTransp, 1, 3, 1, 1) # set/add to layout grpPoles.setLayout(lytPoles) layout.addWidget(grpPoles) # ok/cancel stuff btnOk = QPushButton("&OK") btnCancel = QPushButton("Cancel") lytButtons = QHBoxLayout() lytButtons.addStretch() lytButtons.addWidget(btnOk) lytButtons.addWidget(btnCancel) layout.addLayout(lytButtons) btnOk.clicked.connect(self.accept) btnCancel.clicked.connect(self.reject) self.setLayout(layout) self.setWindowTitle("Plot style")
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 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)
class PlotStyleDlg(QDialog): def __init__(self, dPlotStyles, parent=None): super(PlotStyleDlg, self).__init__(parent) self.dPlotStyles = dPlotStyles settings = QSettings("alberese", "geocouche") layout = QVBoxLayout() # great circle settings grpGreatCircles = QGroupBox("Great circles") lytGreatCircles = QGridLayout() # line color lytGreatCircles.addWidget(QLabel("Line color"), 0, 0, 1, 1) self.btnLineColor = QgsColorButton() line_color = self.dPlotStyles["line_color"] self.btnLineColor.setColor(QColor(line_color)) lytGreatCircles.addWidget(self.btnLineColor, 0, 1, 1, 1) # line style lytGreatCircles.addWidget(QLabel("Line style"), 0, 2, 1, 1) self.cmbLineStyle = QComboBox() self.cmbLineStyle.insertItems(0, ltLineStyles) line_style = self.dPlotStyles["line_style"] line_style_ndx = ltLineStyles.index( line_style) if line_style in ltLineStyles else 0 self.cmbLineStyle.setCurrentIndex(line_style_ndx) lytGreatCircles.addWidget(self.cmbLineStyle, 0, 3, 1, 1) # line thickness lytGreatCircles.addWidget(QLabel("Line width"), 1, 0, 1, 1) self.cmbLineWidth = QComboBox() lnLineThickness = [1, 2, 3, 4, 5, 6] ltLineThicknVals = [str(val) + " pt(s)" for val in lnLineThickness] self.cmbLineWidth.insertItems(0, ltLineThicknVals) line_thickn = self.dPlotStyles["line_width"] line_thickn_ndx = ltLineThicknVals.index( line_thickn) if line_thickn in ltLineThicknVals else 0 self.cmbLineWidth.setCurrentIndex(line_thickn_ndx) lytGreatCircles.addWidget(self.cmbLineWidth, 1, 1, 1, 1) # line transparency lytGreatCircles.addWidget(QLabel("Line transp."), 1, 2, 1, 1) self.cmbLineTransp = QComboBox() lnLineTransparencies = [0, 25, 50, 75] ltLineTranspPrcntVals = [ str(val) + "%" for val in lnLineTransparencies ] self.cmbLineTransp.insertItems(0, ltLineTranspPrcntVals) line_transp = self.dPlotStyles["line_transp"] line_transp_ndx = ltLineTranspPrcntVals.index( line_transp) if line_transp in ltLineTranspPrcntVals else 0 self.cmbLineTransp.setCurrentIndex(line_transp_ndx) lytGreatCircles.addWidget(self.cmbLineTransp, 1, 3, 1, 1) # set/add to layout grpGreatCircles.setLayout(lytGreatCircles) layout.addWidget(grpGreatCircles) # pole settings grpPoles = QGroupBox("Poles") lytPoles = QGridLayout() # marker color lytPoles.addWidget(QLabel("Marker color"), 0, 0, 1, 1) self.btnPointColor = QgsColorButton() point_color = self.dPlotStyles["marker_color"] self.btnPointColor.setColor(QColor(point_color)) lytPoles.addWidget(self.btnPointColor, 0, 1, 1, 1) # marker style lytPoles.addWidget(QLabel("Marker style"), 0, 2, 1, 1) self.cmbPointStyle = QComboBox() self.cmbPointStyle.insertItems(0, list(ltMarkerStyles.keys())) point_style = self.dPlotStyles["marker_style"] point_style_ndx = list( ltMarkerStyles.keys()).index(point_style) if point_style in list( ltMarkerStyles.keys()) else 0 self.cmbPointStyle.setCurrentIndex(point_style_ndx) lytPoles.addWidget(self.cmbPointStyle, 0, 3, 1, 1) # marker size lytPoles.addWidget(QLabel("Marker size"), 1, 0, 1, 1) lnPointSizes = [2, 4, 6, 8, 10, 15, 20] self.cmbPointSize = QComboBox() ltPointSizeVals = [str(val) + " pt(s)" for val in lnPointSizes] self.cmbPointSize.insertItems(0, ltPointSizeVals) point_size = self.dPlotStyles["marker_size"] point_style_ndx = ltPointSizeVals.index( point_size) if point_size in ltPointSizeVals else 2 self.cmbPointSize.setCurrentIndex(point_style_ndx) lytPoles.addWidget(self.cmbPointSize, 1, 1, 1, 1) # marker transparency lytPoles.addWidget(QLabel("Marker transp."), 1, 2, 1, 1) lnPointTransparencies = [0, 25, 50, 75] self.cmbPointTransp = QComboBox() ltPointTranspPrcntVals = [ str(val) + "%" for val in lnPointTransparencies ] self.cmbPointTransp.insertItems(0, ltPointTranspPrcntVals) point_transp = self.dPlotStyles["marker_transp"] point_transp_ndx = ltPointTranspPrcntVals.index( point_transp) if point_transp in ltPointTranspPrcntVals else 0 self.cmbPointTransp.setCurrentIndex(point_transp_ndx) lytPoles.addWidget(self.cmbPointTransp, 1, 3, 1, 1) # set/add to layout grpPoles.setLayout(lytPoles) layout.addWidget(grpPoles) # ok/cancel stuff btnOk = QPushButton("&OK") btnCancel = QPushButton("Cancel") lytButtons = QHBoxLayout() lytButtons.addStretch() lytButtons.addWidget(btnOk) lytButtons.addWidget(btnCancel) layout.addLayout(lytButtons) btnOk.clicked.connect(self.accept) btnCancel.clicked.connect(self.reject) self.setLayout(layout) self.setWindowTitle("Plot style")
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 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 QrCodeLayoutItemWidget(QgsLayoutItemBaseWidget): # pylint: disable=too-few-public-methods """Widget for configuring a QrCodeLayoutItem.""" def __init__(self, parent, layout_object): super().__init__(parent, layout_object) self._qrcode_item = layout_object self.message_bar = None self.setPanelTitle(self.tr('QR Code Properties')) self._init_widgets(layout_object) self._update_gui_values() def _init_widgets(self, layout_object): """Initialize widgets""" lbl_title = QLabel() lbl_title.setStyleSheet( 'padding: 2px; font-weight: bold; background-color: ' 'rgb(200, 200, 200);') lbl_title.setText(self.tr('QR Code')) self._cd_value_widget = CodeValueWidget(self) self._cd_value_widget.value_changed.connect( self._on_code_value_changed) value_groupbox = QgsCollapsibleGroupBoxBasic(self.tr('Data')) gp_layout = QVBoxLayout() gp_layout.setContentsMargins(0, 0, 0, 0) gp_layout.addWidget(self._cd_value_widget) value_groupbox.setLayout(gp_layout) # Item appearance appearance_groupbox = QgsCollapsibleGroupBoxBasic( self.tr('Appearance')) appearance_layout = QGridLayout() # Data color lbl_data_clr = QLabel(self.tr('Data color')) self._data_clr_btn = QgsColorButton() self._data_clr_btn.setColorDialogTitle(self.tr('Select Data Color')) self._data_clr_btn.setContext('composer') self._data_clr_btn.setAllowOpacity(False) self._data_clr_btn.colorChanged.connect(self.on_data_color_changed) appearance_layout.addWidget(lbl_data_clr, 0, 0) appearance_layout.addWidget(self._data_clr_btn, 0, 1) appearance_layout.setColumnStretch(2, 1) # Background color lbl_background_clr = QLabel(self.tr('Background color')) self._background_clr_btn = QgsColorButton() self._background_clr_btn.setColorDialogTitle( self.tr('Select Background Color')) self._background_clr_btn.setContext('composer') self._background_clr_btn.setAllowOpacity(False) self._background_clr_btn.colorChanged.connect( self.on_background_color_changed) appearance_layout.addWidget(lbl_background_clr, 1, 0) appearance_layout.addWidget(self._background_clr_btn, 1, 1) appearance_groupbox.setLayout(appearance_layout) # Properties widget self._prop_widget = QgsLayoutItemPropertiesWidget(self, layout_object) self._prop_widget.showBackgroundGroup(False) # Add widgets to layout layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(lbl_title) layout.addWidget(value_groupbox) layout.addWidget(appearance_groupbox) layout.addWidget(self._prop_widget) # Set layout self.setLayout(layout) def _on_code_value_changed(self, txt): # Slot raised when the code value changes. self._qrcode_item.beginCommand(self.tr('Change code value'), QgsLayoutItem.UndoLabelText) self._qrcode_item.blockSignals(True) self._qrcode_item.code_value = txt self._qrcode_item.blockSignals(False) self._qrcode_item.endCommand() def setNewItem(self, item): """ Set widget properties to sync with item properties. """ if item.type() != QR_CODE_TYPE: return False self._qrcode_item = item self._prop_widget.setItem(self._qrcode_item) self._update_gui_values() return True def _update_gui_values(self): # Updates values of widgets based on item properties. self._cd_value_widget.block_value_widget_signals(True) self._cd_value_widget.code_value = self._qrcode_item.code_value self._cd_value_widget.value_text_edit.moveCursor( QTextCursor.End, QTextCursor.MoveAnchor) self._cd_value_widget.block_value_widget_signals(False) self._data_clr_btn.blockSignals(True) self._data_clr_btn.setColor( color_from_name(self._qrcode_item.data_color, '#000000')) self._data_clr_btn.blockSignals(False) self._background_clr_btn.blockSignals(True) self._background_clr_btn.setColor( color_from_name(self._qrcode_item.bg_color, '#FFFFFF')) self._background_clr_btn.blockSignals(False) def setDesignerInterface(self, iface): """ Use iface to set the message_bar. """ super().setDesignerInterface(iface) self.message_bar = iface.messageBar() def on_data_color_changed(self, color): """ Slot raised when new data color is set. """ self._qrcode_item.beginCommand(self.tr('Change data color'), QgsLayoutItem.UndoPictureFillColor) self._qrcode_item.blockSignals(True) self._qrcode_item.data_color = color.name() self._qrcode_item.blockSignals(False) self._qrcode_item.endCommand() def on_background_color_changed(self, color): """ Slot raised when new background color is set. """ self._qrcode_item.beginCommand(self.tr('Change background color'), QgsLayoutItem.UndoPictureFillColor) self._qrcode_item.blockSignals(True) self._qrcode_item.bg_color = color.name() self._qrcode_item.blockSignals(False) self._qrcode_item.endCommand()
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 Serval(object): LINE_SELECTION = "line" POLYGON_SELECTION = "polygon" RGB = "RGB" SINGLE_BAND = "Single band" def __init__(self, iface): self.iface = iface self.canvas = self.iface.mapCanvas() self.plugin_dir = os.path.dirname(__file__) self.uc = UserCommunication(iface, 'Serval') self.load_settings() self.raster = None self.handler = None self.spin_boxes = None self.exp_dlg = None self.exp_builder = None self.block_pts_layer = None self.px, self.py = [0, 0] self.last_point = QgsPointXY(0, 0) self.rbounds = None self.changes = dict() # dict with rasters changes {raster_id: RasterChanges instance} self.project = QgsProject.instance() self.crs_transform = None self.all_touched = None self.selection_mode = None self.spatial_index_time = dict() # {layer_id: creation time} self.spatial_index = dict() # {layer_id: spatial index} self.selection_layers_count = 1 self.debug = DEBUG self.logger = get_logger() if self.debug else None self.menu = u'Serval' self.actions = [] self.actions_always_on = [] self.toolbar = self.iface.addToolBar(u'Serval Main Toolbar') self.toolbar.setObjectName(u'Serval Main Toolbar') self.toolbar.setToolTip(u'Serval Main Toolbar') self.sel_toolbar = self.iface.addToolBar(u'Serval Selection Toolbar') self.sel_toolbar.setObjectName(u'Serval Selection Toolbar') self.sel_toolbar.setToolTip(u'Serval Selection Toolbar') # Map tools self.probe_tool = QgsMapToolEmitPoint(self.canvas) self.probe_tool.setObjectName('ServalProbeTool') self.probe_tool.setCursor(QCursor(QPixmap(icon_path('probe_tool.svg')), hotX=2, hotY=22)) self.probe_tool.canvasClicked.connect(self.point_clicked) self.draw_tool = QgsMapToolEmitPoint(self.canvas) self.draw_tool.setObjectName('ServalDrawTool') self.draw_tool.setCursor(QCursor(QPixmap(icon_path('draw_tool.svg')), hotX=2, hotY=22)) self.draw_tool.canvasClicked.connect(self.point_clicked) self.selection_tool = RasterCellSelectionMapTool(self.iface, self.uc, self.raster, debug=self.debug) self.selection_tool.setObjectName('RasterSelectionTool') self.map_tool_btn = dict() # {map tool: button activating the tool} self.iface.currentLayerChanged.connect(self.set_active_raster) self.project.layersAdded.connect(self.set_active_raster) self.canvas.mapToolSet.connect(self.check_active_tool) self.register_exp_functions() def load_settings(self): """Return plugin settings dict - default values are overriden by user prefered values from QSettings.""" self.default_settings = { "undo_steps": {"value": 3, "vtype": int}, } self.settings = dict() s = QSettings() s.beginGroup("serval") for k, v in self.default_settings.items(): user_val = s.value(k, v["value"], v["vtype"]) self.settings[k] = user_val def edit_settings(self): """Open dialog with plugin settings.""" s = QSettings() s.beginGroup("serval") k = "undo_steps" cur_val = self.settings[k] val_type = self.default_settings[k]["vtype"] cur_steps = s.value(k, cur_val, val_type) label = 'Nr of Undo/Redo steps:' steps, ok = QInputDialog.getInt(None, "Serval Settings", label, cur_steps) if not ok: return if steps >= 0: s.setValue("undo_steps", steps) self.load_settings() self.uc.show_info("Some new settings may require QGIS restart.") def initGui(self): _ = self.add_action( 'serval_icon.svg', text=u'Show Serval Toolbars', add_to_menu=True, callback=self.show_toolbar, always_on=True, ) _ = self.add_action( 'serval_icon.svg', text=u'Hide Serval Toolbars', add_to_menu=True, callback=self.hide_toolbar, always_on=True, ) self.probe_btn = self.add_action( 'probe.svg', text="Probe raster", callback=self.activate_probing, add_to_toolbar=self.toolbar, checkable=True, ) self.map_tool_btn[self.probe_tool] = self.probe_btn self.color_btn = QgsColorButton() self.color_btn.setColor(Qt.gray) self.color_btn.setMinimumSize(QSize(40, 24)) self.color_btn.setMaximumSize(QSize(40, 24)) self.toolbar.addWidget(self.color_btn) self.color_picker_connection(connect=True) self.color_btn.setDisabled(True) self.toolbar.addWidget(QLabel("Band:")) self.bands_cbo = QComboBox() self.bands_cbo.addItem("1", 1) self.toolbar.addWidget(self.bands_cbo) self.bands_cbo.currentIndexChanged.connect(self.update_active_bands) self.bands_cbo.setDisabled(True) self.spin_boxes = BandBoxes() self.toolbar.addWidget(self.spin_boxes) self.spin_boxes.enter_hit.connect(self.apply_spin_box_values) self.draw_btn = self.add_action( 'draw.svg', text="Apply Value(s) To Single Cell", callback=self.activate_drawing, add_to_toolbar=self.toolbar, checkable=True, ) self.map_tool_btn[self.draw_tool] = self.draw_btn self.apply_spin_box_values_btn = self.add_action( 'apply_const_value.svg', text="Apply Value(s) to Selection", callback=self.apply_spin_box_values, add_to_toolbar=self.toolbar, ) self.gom_btn = self.add_action( 'apply_nodata_value.svg', text="Apply NoData to Selection", callback=self.apply_nodata_value, add_to_toolbar=self.toolbar, ) self.exp_dlg_btn = self.add_action( 'apply_expression_value.svg', text="Apply Expression Value To Selection", callback=self.define_expression, add_to_toolbar=self.toolbar, checkable=False, ) self.low_pass_filter_btn = self.add_action( 'apply_low_pass_filter.svg', text="Apply Low-Pass 3x3 Filter To Selection", callback=self.apply_low_pass_filter, add_to_toolbar=self.toolbar, checkable=False, ) self.undo_btn = self.add_action( 'undo.svg', text="Undo", callback=self.undo, add_to_toolbar=self.toolbar, ) self.redo_btn = self.add_action( 'redo.svg', text="Redo", callback=self.redo, add_to_toolbar=self.toolbar, ) self.set_nodata_btn = self.add_action( 'set_nodata.svg', text="Edit Raster NoData Values", callback=self.set_nodata, add_to_toolbar=self.toolbar, ) self.settings_btn = self.add_action( 'edit_settings.svg', text="Serval Settings", callback=self.edit_settings, add_to_toolbar=self.toolbar, always_on=True, ) self.show_help = self.add_action( 'help.svg', text="Help", add_to_menu=True, callback=self.show_website, add_to_toolbar=self.toolbar, always_on=True, ) # Selection Toolbar line_width_icon = QIcon(icon_path("line_width.svg")) line_width_lab = QLabel() line_width_lab.setPixmap(line_width_icon.pixmap(22, 12)) self.sel_toolbar.addWidget(line_width_lab) self.line_width_sbox = QgsDoubleSpinBox() self.line_width_sbox.setMinimumSize(QSize(50, 24)) self.line_width_sbox.setMaximumSize(QSize(50, 24)) # self.line_width_sbox.setButtonSymbols(QAbstractSpinBox.NoButtons) self.line_width_sbox.setValue(1) self.line_width_sbox.setMinimum(0.01) self.line_width_sbox.setShowClearButton(False) self.line_width_sbox.setToolTip("Selection Line Width") self.line_width_sbox.valueChanged.connect(self.update_selection_tool) self.width_unit_cbo = QComboBox() self.width_units = ("map units", "pixel width", "pixel height", "hairline",) for u in self.width_units: self.width_unit_cbo.addItem(u) self.width_unit_cbo.setToolTip("Selection Line Width Unit") self.sel_toolbar.addWidget(self.line_width_sbox) self.sel_toolbar.addWidget(self.width_unit_cbo) self.width_unit_cbo.currentIndexChanged.connect(self.update_selection_tool) self.line_select_btn = self.add_action( 'select_line.svg', text="Select Raster Cells by Line", callback=self.activate_line_selection, add_to_toolbar=self.sel_toolbar, checkable=True, ) self.polygon_select_btn = self.add_action( 'select_polygon.svg', text="Select Raster Cells by Polygon", callback=self.activate_polygon_selection, add_to_toolbar=self.sel_toolbar, checkable=True, ) self.selection_from_layer_btn = self.add_action( 'select_from_layer.svg', text="Create Selection From Layer", callback=self.selection_from_layer, add_to_toolbar=self.sel_toolbar, ) self.selection_to_layer_btn = self.add_action( 'selection_to_layer.svg', text="Create Memory Layer From Selection", callback=self.selection_to_layer, add_to_toolbar=self.sel_toolbar, ) self.clear_selection_btn = self.add_action( 'clear_selection.svg', text="Clear selection", callback=self.clear_selection, add_to_toolbar=self.sel_toolbar, ) self.toggle_all_touched_btn = self.add_action( 'all_touched.svg', text="Toggle All Touched Get Selected", callback=self.toggle_all_touched, checkable=True, checked=True, add_to_toolbar=self.sel_toolbar, ) self.all_touched = True self.enable_toolbar_actions(enable=False) self.check_undo_redo_btns() def add_action(self, icon_name, callback=None, text="", enabled_flag=True, add_to_menu=False, add_to_toolbar=None, status_tip=None, whats_this=None, checkable=False, checked=False, always_on=False): icon = QIcon(icon_path(icon_name)) action = QAction(icon, text, self.iface.mainWindow()) action.triggered.connect(callback) action.setEnabled(enabled_flag) action.setCheckable(checkable) action.setChecked(checked) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar is not None: add_to_toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) if always_on: self.actions_always_on.append(action) return action def unload(self): self.changes = None if self.selection_tool: self.selection_tool.reset() if self.spin_boxes is not None: self.spin_boxes.remove_spinboxes() for action in self.actions: self.iface.removePluginMenu('Serval', action) self.iface.removeToolBarIcon(action) del self.toolbar del self.sel_toolbar self.iface.actionPan().trigger() self.unregister_exp_functions() def show_toolbar(self): if self.toolbar: self.toolbar.show() self.sel_toolbar.show() def hide_toolbar(self): if self.toolbar: self.toolbar.hide() self.sel_toolbar.hide() @staticmethod def register_exp_functions(): QgsExpression.registerFunction(nearest_feature_attr_value) QgsExpression.registerFunction(nearest_pt_on_line_interpolate_z) QgsExpression.registerFunction(intersecting_features_attr_average) QgsExpression.registerFunction(interpolate_from_mesh) @staticmethod def unregister_exp_functions(): QgsExpression.unregisterFunction('nearest_feature_attr_value') QgsExpression.unregisterFunction('nearest_pt_on_line_interpolate_z') QgsExpression.unregisterFunction('intersecting_features_attr_average') QgsExpression.unregisterFunction('interpolate_from_mesh') def uncheck_all_btns(self): self.probe_btn.setChecked(False) self.draw_btn.setChecked(False) self.gom_btn.setChecked(False) self.line_select_btn.setChecked(False) self.polygon_select_btn.setChecked(False) def check_active_tool(self, cur_tool): self.uncheck_all_btns() if cur_tool in self.map_tool_btn: self.map_tool_btn[cur_tool].setChecked(True) if cur_tool == self.selection_tool: if self.selection_mode == self.LINE_SELECTION: self.line_select_btn.setChecked(True) else: self.polygon_select_btn.setChecked(True) def activate_probing(self): self.mode = 'probe' self.canvas.setMapTool(self.probe_tool) def define_expression(self): if not self.selection_tool.selected_geometries: self.uc.bar_warn("No selection for raster layer. Select some cells and retry...") return self.handler.select(self.selection_tool.selected_geometries, all_touched_cells=self.all_touched) self.handler.create_cell_pts_layer() if self.handler.cell_pts_layer.featureCount() == 0: self.uc.bar_warn("No selection for raster layer. Select some cells and retry...") return self.exp_dlg = QgsExpressionBuilderDialog(self.handler.cell_pts_layer) self.exp_builder = self.exp_dlg.expressionBuilder() self.exp_dlg.accepted.connect(self.apply_exp_value) self.exp_dlg.show() def apply_exp_value(self): if not self.exp_dlg.expressionText() or not self.exp_builder.isExpressionValid(): return QApplication.setOverrideCursor(Qt.WaitCursor) exp = self.exp_dlg.expressionText() idx = self.handler.cell_pts_layer.addExpressionField(exp, QgsField('exp_val', QVariant.Double)) self.handler.exp_field_idx = idx self.handler.write_block() QApplication.restoreOverrideCursor() self.raster.triggerRepaint() def activate_drawing(self): self.mode = 'draw' self.canvas.setMapTool(self.draw_tool) def get_cur_line_width(self): width_coef = { "map units": 1., "pixel width": self.raster.rasterUnitsPerPixelX(), "pixel height": self.raster.rasterUnitsPerPixelY(), "hairline": 0.000001, } return self.line_width_sbox.value() * width_coef[self.width_unit_cbo.currentText()] def set_selection_tool(self, mode): if self.raster is None: self.uc.bar_warn("Select a raster layer") return self.selection_mode = mode self.selection_tool.init_tool(self.raster, mode=self.selection_mode, line_width=self.get_cur_line_width()) self.selection_tool.set_prev_tool(self.canvas.mapTool()) self.canvas.setMapTool(self.selection_tool) def activate_line_selection(self): self.set_selection_tool(self.LINE_SELECTION) def activate_polygon_selection(self): self.set_selection_tool(self.POLYGON_SELECTION) def update_selection_tool(self): """Reactivate the selection tool with updated line width and units.""" if self.selection_mode == self.LINE_SELECTION: self.activate_line_selection() elif self.selection_mode == self.POLYGON_SELECTION: self.activate_polygon_selection() else: pass def apply_values(self, new_values): QApplication.setOverrideCursor(Qt.WaitCursor) self.handler.select(self.selection_tool.selected_geometries, all_touched_cells=self.all_touched) self.handler.write_block(new_values) QApplication.restoreOverrideCursor() self.raster.triggerRepaint() def apply_values_single_cell(self, new_vals): """Create single cell selection and apply the new values.""" cp = self.last_point if self.logger: self.logger.debug(f"Changing single cell for pt {cp}") col, row = self.handler.point_to_index([cp.x(), cp.y()]) px, py = self.handler.index_to_point(row, col, upper_left=False) d = 0.001 bbox = QgsRectangle(px - d, py - d, px + d, py + d) if self.logger: self.logger.debug(f"Changing single cell in {bbox}") QApplication.setOverrideCursor(Qt.WaitCursor) self.handler.select([QgsGeometry.fromRect(bbox)], all_touched_cells=False, transform=False) self.handler.write_block(new_vals) QApplication.restoreOverrideCursor() self.raster.triggerRepaint() def apply_spin_box_values(self): if not self.selection_tool.selected_geometries: return self.apply_values(self.spin_boxes.get_values()) def apply_nodata_value(self): if not self.selection_tool.selected_geometries: return self.apply_values(self.handler.nodata_values) def apply_low_pass_filter(self): QApplication.setOverrideCursor(Qt.WaitCursor) self.handler.select(self.selection_tool.selected_geometries, all_touched_cells=self.all_touched) self.handler.write_block(low_pass_filter=True) QApplication.restoreOverrideCursor() self.raster.triggerRepaint() def clear_selection(self): if self.selection_tool: self.selection_tool.clear_all_selections() def selection_from_layer(self): """Create a new selection from layer.""" self.selection_tool.init_tool(self.raster, mode=self.POLYGON_SELECTION, line_width=self.get_cur_line_width()) dlg = LayerSelectDialog() if not dlg.exec_(): return cur_layer = dlg.cbo.currentLayer() if not cur_layer.type() == QgsMapLayerType.VectorLayer: return self.selection_tool.selection_from_layer(cur_layer) def selection_to_layer(self): """Create a memory layer from current selection""" geoms = self.selection_tool.selected_geometries if geoms is None or not self.raster: return crs_str = self.raster.crs().toProj() nr = self.selection_layers_count self.selection_layers_count += 1 mlayer = QgsVectorLayer(f"Polygon?crs={crs_str}&field=fid:int", f"Raster selection {nr}", "memory") fields = mlayer.dataProvider().fields() features = [] for i, geom in enumerate(geoms): feat = QgsFeature(fields) feat["fid"] = i + 1 feat.setGeometry(geom) features.append(feat) mlayer.dataProvider().addFeatures(features) self.project.addMapLayer(mlayer) def toggle_all_touched(self): """Toggle selection mode.""" # button is toggled automatically when clicked, just update the attribute self.all_touched = self.toggle_all_touched_btn.isChecked() def point_clicked(self, point=None, button=None): if self.raster is None: self.uc.bar_warn("Choose a raster to work with...", dur=3) return if self.logger: self.logger.debug(f"Clicked point in canvas CRS: {point if point else self.last_point}") if point is None: ptxy_in_src_crs = self.last_point else: if self.crs_transform: if self.logger: self.logger.debug(f"Transforming clicked point {point}") try: ptxy_in_src_crs = self.crs_transform.transform(point) except QgsCsException as err: self.uc.show_warn( "Point coordinates transformation failed! Check the raster projection:\n\n{}".format(repr(err))) return else: ptxy_in_src_crs = QgsPointXY(point.x(), point.y()) if self.logger: self.logger.debug(f"Clicked point in raster CRS: {ptxy_in_src_crs}") self.last_point = ptxy_in_src_crs ident_vals = self.handler.provider.identify(ptxy_in_src_crs, QgsRaster.IdentifyFormatValue).results() cur_vals = list(ident_vals.values()) # check if the point is within active raster extent if not self.rbounds[0] <= ptxy_in_src_crs.x() <= self.rbounds[2]: self.uc.bar_info("Out of x bounds", dur=3) return if not self.rbounds[1] <= ptxy_in_src_crs.y() <= self.rbounds[3]: self.uc.bar_info("Out of y bounds", dur=3) return if self.mode == 'draw': new_vals = self.spin_boxes.get_values() if self.logger: self.logger.debug(f"Applying const value {new_vals}") self.apply_values_single_cell(new_vals) else: self.spin_boxes.set_values(cur_vals) if 2 < self.handler.bands_nr < 5: self.color_picker_connection(connect=False) self.color_btn.setColor(QColor(*self.spin_boxes.get_values()[:4])) self.color_picker_connection(connect=True) def set_values_from_picker(self, c): """Set bands spinboxes values after color change in the color picker""" values = None if self.handler.bands_nr > 2: values = [c.red(), c.green(), c.blue()] if self.handler.bands_nr == 4: values.append(c.alpha()) if values: self.spin_boxes.set_values(values) def set_nodata(self): """Set NoData value(s) for each band of current raster.""" if not self.raster: self.uc.bar_warn('Select a raster layer to define/change NoData value!') return if self.handler.provider.userNoDataValues(1): note = '\nNote: there is a user defined NODATA value.\nCheck the raster properties (Transparency).' else: note = '' dt = self.handler.provider.dataType(1) # current NODATA value if self.handler.provider.sourceHasNoDataValue(1): cur_nodata = self.handler.provider.sourceNoDataValue(1) if dt < 6: cur_nodata = '{0:d}'.format(int(float(cur_nodata))) else: cur_nodata = '' label = 'Define/change raster NODATA value.\n\n' label += 'Raster src_data type: {}.{}'.format(dtypes[dt]['name'], note) nd, ok = QInputDialog.getText(None, "Define NODATA Value", label, QLineEdit.Normal, str(cur_nodata)) if not ok: return if not is_number(nd): self.uc.show_warn('Wrong NODATA value!') return new_nodata = int(nd) if dt < 6 else float(nd) # set the NODATA value for each band res = [] for nr in self.handler.bands_range: res.append(self.handler.provider.setNoDataValue(nr, new_nodata)) self.handler.provider.sourceHasNoDataValue(nr) if False in res: self.uc.show_warn('Setting new NODATA value failed!') else: self.uc.bar_info('Successful setting new NODATA values!', dur=2) self.set_active_raster() self.raster.triggerRepaint() def check_undo_redo_btns(self): """Enable/Disable undo and redo buttons based on availability of undo/redo for current raster.""" self.undo_btn.setDisabled(True) self.redo_btn.setDisabled(True) if self.raster is None or self.raster.id() not in self.changes: return changes = self.changes[self.raster.id()] if changes.nr_undos() > 0: self.undo_btn.setEnabled(True) if changes.nr_redos() > 0: self.redo_btn.setEnabled(True) def enable_toolbar_actions(self, enable=True): """Enable / disable all toolbar actions but Help (for vectors and unsupported rasters)""" for widget in self.actions + [self.width_unit_cbo, self.line_width_sbox]: widget.setEnabled(enable) if widget in self.actions_always_on: widget.setEnabled(True) self.spin_boxes.enable(enable) @staticmethod def check_layer(layer): """Check if we can work with the raster""" if layer is None: return False if layer.type() != QgsMapLayerType.RasterLayer: return False if layer.providerType() != 'gdal': return False if all([ layer.isValid(), layer.crs() is not None, check_gdal_driver_create_option(layer), # GDAL driver has CREATE option os.path.isfile(layer.dataProvider().dataSourceUri()), # is it a local file? ]): return True else: return False def set_bands_cbo(self): self.bands_cbo.currentIndexChanged.disconnect(self.update_active_bands) self.bands_cbo.clear() for band in self.handler.bands_range: self.bands_cbo.addItem(f"{band}", [band]) if self.handler.bands_nr > 1: self.bands_cbo.addItem(self.RGB, [1, 2, 3]) self.bands_cbo.setCurrentIndex(0) self.bands_cbo.currentIndexChanged.connect(self.update_active_bands) def update_active_bands(self, idx): bands = self.bands_cbo.currentData() self.handler.active_bands = bands self.spin_boxes.create_spinboxes(bands, self.handler.data_types, self.handler.nodata_values) self.color_btn.setEnabled(len(bands) > 1) self.exp_dlg_btn.setEnabled(len(bands) == 1) def set_active_raster(self): """Active layer has changed - check if it is a raster layer and prepare it for the plugin""" old_spin_boxes_values = self.spin_boxes.get_values() self.crs_transform = None layer = self.iface.activeLayer() if self.check_layer(layer): self.raster = layer self.crs_transform = None if self.project.crs() == self.raster.crs() else \ QgsCoordinateTransform(self.project.crs(), self.raster.crs(), self.project) self.handler = RasterHandler(self.raster, self.uc, self.debug) supported, unsupported_type = self.handler.write_supported() if supported: self.enable_toolbar_actions() self.set_bands_cbo() self.spin_boxes.create_spinboxes(self.handler.active_bands, self.handler.data_types, self.handler.nodata_values) if self.handler.bands_nr == len(old_spin_boxes_values): self.spin_boxes.set_values(old_spin_boxes_values) self.bands_cbo.setEnabled(self.handler.bands_nr > 1) self.color_btn.setEnabled(len(self.handler.active_bands) > 1) self.rbounds = self.raster.extent().toRectF().getCoords() self.handler.raster_changed.connect(self.add_to_undo) if self.raster.id() not in self.changes: self.changes[self.raster.id()] = RasterChanges(nr_to_keep=self.settings["undo_steps"]) else: msg = f"The raster has unsupported src_data type: {unsupported_type}" msg += "\nServal can't work with it, sorry..." self.uc.show_warn(msg) self.enable_toolbar_actions(enable=False) self.reset_raster() else: # unsupported raster self.enable_toolbar_actions(enable=False) self.reset_raster() self.check_undo_redo_btns() def add_to_undo(self, change): """Add the old and new blocks to undo stack.""" self.changes[self.raster.id()].add_change(change) self.check_undo_redo_btns() if self.logger: self.logger.debug(self.get_undo_redo_values()) def get_undo_redo_values(self): changes = self.changes[self.raster.id()] return f"nr undos: {changes.nr_undos()}, redos: {changes.nr_redos()}" def undo(self): undo_data = self.changes[self.raster.id()].undo() self.handler.write_block_undo(undo_data) self.raster.triggerRepaint() self.check_undo_redo_btns() def redo(self): redo_data = self.changes[self.raster.id()].redo() self.handler.write_block_undo(redo_data) self.raster.triggerRepaint() self.check_undo_redo_btns() def reset_raster(self): self.raster = None self.color_btn.setDisabled(True) def color_picker_connection(self, connect=True): if connect: self.color_btn.colorChanged.connect(self.set_values_from_picker) else: self.color_btn.colorChanged.disconnect(self.set_values_from_picker) @staticmethod def show_website(): QDesktopServices.openUrl(QUrl("https://github.com/lutraconsulting/serval/blob/master/Serval/docs/user_manual.md")) def recreate_spatial_index(self, layer): """Check if spatial index exists for the layer and if it is relatively old and eventually recreate it.""" ctime = self.spatial_index_time[layer.id()] if layer.id() in self.spatial_index_time else None if ctime is None or datetime.now() - ctime > timedelta(seconds=30): self.spatial_index = QgsSpatialIndex(layer.getFeatures(), None, QgsSpatialIndex.FlagStoreFeatureGeometries) self.spatial_index_time[layer.id()] = datetime.now() def get_nearest_feature(self, pt_feat, vlayer_id): """Given the point feature, return nearest feature from vlayer.""" vlayer = self.project.mapLayer(vlayer_id) self.recreate_spatial_index(vlayer) ptxy = pt_feat.geometry().asPoint() near_fid = self.spatial_index.nearestNeighbor(ptxy)[0] return vlayer.getFeature(near_fid) def nearest_feature_attr_value(self, pt_feat, vlayer_id, attr_name): """Find nearest feature to pt_feat and return its attr_name attribute value.""" near_feat = self.get_nearest_feature(pt_feat, vlayer_id) return near_feat[attr_name] def nearest_pt_on_line_interpolate_z(self, pt_feat, vlayer_id): """Find nearest line feature to pt_feat and interpolate z value from vertices.""" near_feat = self.get_nearest_feature(pt_feat, vlayer_id) near_geom = near_feat.geometry() closest_pt_dist = near_geom.lineLocatePoint(pt_feat.geometry()) closest_pt = near_geom.interpolate(closest_pt_dist) return closest_pt.get().z() def intersecting_features_attr_average(self, pt_feat, vlayer_id, attr_name, only_center): """ Find all features intersecting current feature (cell center, or raster cell polygon) and calculate average value of their attr_name attribute. """ vlayer = self.project.mapLayer(vlayer_id) self.recreate_spatial_index(vlayer) ptxy = pt_feat.geometry().asPoint() pt_x, pt_y = ptxy.x(), ptxy.y() dxy = 0.001 half_pix_x = self.handler.pixel_size_x / 2. half_pix_y = self.handler.pixel_size_y / 2. if only_center: cell = QgsRectangle(pt_x, pt_y, pt_x + dxy, pt_y + dxy) else: cell = QgsRectangle(pt_x - half_pix_x, pt_y - half_pix_y, pt_x + half_pix_x, pt_y + half_pix_y) inter_fids = self.spatial_index.intersects(cell) values = [] for fid in inter_fids: feat = vlayer.getFeature(fid) if not feat.geometry().intersects(cell): continue val = feat[attr_name] if not is_number(val): continue values.append(val) if len(values) == 0: return None return sum(values) / float(len(values)) def interpolate_from_mesh(self, pt_feat, mesh_layer_id, group, dataset, above_existing): """Interpolate from mesh.""" mesh_layer = self.project.mapLayer(mesh_layer_id) ptxy = pt_feat.geometry().asPoint() dataset_val = mesh_layer.datasetValue(QgsMeshDatasetIndex(group, dataset), ptxy) val = dataset_val.scalar() if math.isnan(val): return val if above_existing: ident_vals = self.handler.provider.identify(ptxy, QgsRaster.IdentifyFormatValue).results() org_val = list(ident_vals.values())[0] if org_val == self.handler.nodata_values[0]: return val return max(org_val, val) else: return val