class loadRteDialog(fields_dialog.fieldsDialog): #parent must have attribute sections def __init__(self, layerBox, parent): fields = ['direction'] super(loadRteDialog, self).__init__(fields=fields, layerBox=layerBox, parent=parent) self.setTooltips({ 'direction': 'Field of layer with direction. Values need to be one of NB,EB,SB,WB,CW,AC' }) self.fileWidget = QgsFileWidget(self) self.layout().insertRow(0, 'File', self.fileWidget) self.buttonBox.rejected.connect(self.hide) self.setWindowTitle('load rte') self.clearMode = True # True=insert at row,False=clear and load self.buttonBox.accepted.connect(self.load) def setclearMode(self, mode): self.clearMode = mode def show(self, clearMode): self.clearMode = clearMode super(loadRteDialog, self).show() def load(self): layer = self.parent().getLayer() p = self.fileWidget.filePath() if not p: iface.messageBar().pushMessage( "manual secbuilder:no file selected", duration=4) return if not self.fieldsSet(): iface.messageBar().pushMessage( "manual secbuilder:direction field not set", duration=4) return directionField = self.getFields()['direction'] labelField = self.parent().getLabelField() with open(p, 'r') as f: self.parent().model.loadRTE(f=f, layer=layer, labelField=labelField, directionField=directionField, row=self.parent().rowBox.value(), clear=self.clearMode) self.hide()
class QvFormNovaMapificacio(QvFormBaseMapificacio): def __init__(self, llegenda, amplada=500, mapificacio=None, simple=True): super().__init__(llegenda, amplada) self.fCSV = mapificacio self.simple = simple self.taulaMostra = None self.setWindowTitle('Afegir capa amb mapa simbòlic') self.layout = QVBoxLayout() self.layout.setSpacing(14) self.setLayout(self.layout) if self.fCSV is None: self.arxiu = QgsFileWidget() self.arxiu.setStorageMode(QgsFileWidget.GetFile) self.arxiu.setDialogTitle('Selecciona fitxer de dades…') self.arxiu.setDefaultRoot(RUTA_LOCAL) self.arxiu.setFilter('Arxius CSV (*.csv)') self.arxiu.setSelectedFilter('Arxius CSV (*.csv)') self.arxiu.lineEdit().setReadOnly(True) self.arxiu.fileChanged.connect(self.arxiuSeleccionat) self.zona = QComboBox(self) self.zona.setEditable(False) self.zona.addItem('Selecciona zona…') self.zona.currentIndexChanged.connect(self.canviaZona) self.mapa = QComboBox(self) self.mapa.setEditable(False) self.mapa.setIconSize(QSize(126, 126)) self.mapa.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.mapa.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.mapa.addItem(QIcon(os.path.join(imatgesDir, 'Àrees.PNG')), 'Àrees') self.mapa.addItem(QIcon(os.path.join(imatgesDir, 'Cercles.PNG')), 'Cercles') self.capa = QLineEdit(self) self.capa.setMaxLength(40) self.tipus = QComboBox(self) self.tipus.setEditable(False) self.tipus.addItem('Selecciona tipus…') self.tipus.addItems(mv.MAP_AGREGACIO.keys()) self.tipus.currentIndexChanged.connect(self.canviaTipus) self.distribucio = QComboBox(self) self.distribucio.setEditable(False) self.distribucio.addItem(next(iter(mv.MAP_DISTRIBUCIO.keys()))) self.calcul = QvComboBoxCamps(self) self.filtre = QvComboBoxCamps(self, multiple=True) self.color = QComboBox(self) self.color.setEditable(False) self.comboColors(self.color) self.metode = QComboBox(self) self.metode.setEditable(False) self.metode.addItems(mv.MAP_METODES.keys()) self.intervals = QSpinBox(self) self.intervals.setMinimum(2) self.intervals.setMaximum(mv.MAP_MAX_CATEGORIES) self.intervals.setSingleStep(1) self.intervals.setValue(4) self.intervals.setSuffix(" (depèn del mètode)") # self.intervals.valueChanged.connect(self.deselectValue) self.bTaula = QPushButton('Veure arxiu') self.bTaula.setEnabled(False) self.bTaula.clicked.connect(self.veureArxiu) self.buttons = QDialogButtonBox() self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.accepted.connect(self.accept) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.rejected.connect(self.cancel) self.buttons.addButton(self.bTaula, QDialogButtonBox.ResetRole) self.gDades = QGroupBox('Agregació de dades') self.lDades = QFormLayout() self.lDades.setSpacing(14) self.gDades.setLayout(self.lDades) if self.fCSV is None: self.lDades.addRow('Arxiu de dades:', self.arxiu) self.lDades.addRow('Zona:', self.zona) self.lDades.addRow("Tipus d'agregació:", self.tipus) self.lDades.addRow('Camp de càlcul:', self.calcul) if self.simple: self.filtre.setVisible(False) self.distribucio.setVisible(False) else: self.lDades.addRow('Filtre:', self.filtre) self.lDades.addRow('Distribució:', self.distribucio) self.gMapa = QGroupBox('Definició del mapa simbòlic') self.lMapa = QFormLayout() self.lMapa.setSpacing(14) self.gMapa.setLayout(self.lMapa) self.lMapa.addRow('Nom de capa:', self.capa) self.lMapa.addRow('Tipus de mapa:', self.mapa) self.gSimb = QGroupBox('Simbologia del mapa') self.lSimb = QFormLayout() self.lSimb.setSpacing(14) self.gSimb.setLayout(self.lSimb) self.lSimb.addRow('Color base:', self.color) self.lSimb.addRow('Mètode classificació:', self.metode) self.lSimb.addRow("Nombre d'intervals:", self.intervals) self.layout.addWidget(self.gDades) self.layout.addWidget(self.gMapa) if self.simple: self.gSimb.setVisible(False) else: self.layout.addWidget(self.gSimb) self.layout.addWidget(self.buttons) self.adjustSize() self.nouArxiu() def exec(self): # La mapificación solo funciona si está instalado el módulo pandas if PANDAS_ENABLED: return super().exec() else: self.msgError(PANDAS_ERROR) return QDialog.Rejected @pyqtSlot() def veureArxiu(self): if self.taulaMostra is not None: self.taulaMostra.show() self.taulaMostra.activateWindow() def campsDB(self, nom): res = [] if nom != '': fich = RUTA_DADES + mv.MAP_ZONES_DB if os.path.isfile(fich): conn = sqlite3.connect('file:' + fich + '?mode=ro', uri=True) conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('select * from ' + nom) # nom.split('.')[0]) row = c.fetchone() # res = [i[0].upper() for i in c.description] res = [i.upper() for i in row.keys()] conn.close() return res def soloPrimerItem(self, combo): combo.setCurrentIndex(0) ultimo = combo.count() - 1 for n in range(ultimo, 0, -1): combo.removeItem(n) @pyqtSlot() def canviaZona(self): self.distribucio.setCurrentIndex(0) self.soloPrimerItem(self.distribucio) if self.zona.currentIndex() > 0: z = self.zona.currentText() campsZona = self.campsDB(mv.MAP_ZONES[z][1]) # Carga combo con distribuciones si el campo correspondiente está en la BBDD for dist, campo in mv.MAP_DISTRIBUCIO.items(): if campo != '' and campo in campsZona: self.distribucio.addItem(dist) @pyqtSlot() def canviaTipus(self): if self.tipus.currentText() == 'Recompte': self.calcul.setCurrentIndex(-1) self.calcul.setEnabled(False) else: self.calcul.setEnabled(True) def borrarArxiu(self): if self.taulaMostra is not None: self.taulaMostra.hide() self.taulaMostra = None self.bTaula.setEnabled(False) self.tipus.setCurrentIndex(0) self.soloPrimerItem(self.zona) self.calcul.clear() self.filtre.clear() def nouArxiu(self): if self.fCSV is None: return # Carga combo con zonas si el campo correspondiente está en el fichero CSV num = 0 for zona, val in mv.MAP_ZONES.items(): if val[1] != '' and self.fCSV.prefixe + QvSqlite.getAlias(val[0]) in self.fCSV.camps: self.zona.addItem(zona) num = num + 1 # Comprobar si la extensión del mapa está limitada if num > 0: extensio = self.fCSV.testExtensioArxiu(mv.MAP_EXTENSIO) if extensio: # Mapa limitado self.comboDelete(self.zona, mv.MAP_TRUE_EXTENSIO) else: # Mapa completo self.comboDelete(self.zona, mv.MAP_FALSE_EXTENSIO) # Ajustar combo de zonas if num == 0: self.msgInfo("El fitxer " + self.fCSV.fZones + " no té cap camp de zona") if hasattr(self, 'arxiu'): self.arxiu.lineEdit().clear() self.arxiu.setFocus() return if num == 1: self.zona.setCurrentIndex(1) self.capa.setFocus() else: self.zona.setFocus() self.taulaMostra = QvEditorCsv(self.fCSV.fZones, [], 'utf-8', self.fCSV.separador, self) self.taulaMostra.setWindowTitle("Vista prèvia d'arxiu geocodificat") self.taulaMostra.setReadOnly(True) self.bTaula.setEnabled(True) self.calcul.setItems(self.fCSV.camps, primer='') self.filtre.setItems(self.fCSV.camps) @pyqtSlot(str) def arxiuSeleccionat(self, nom): if nom == '': return self.borrarArxiu() self.fCSV = QvMapificacio(nom) self.nouArxiu() def validaSortida(self, nom): fSalida = self.fCSV.nomArxiuSortida(self.fCSV.netejaString(nom, True)) return self.msgSobreescriure(fSalida) def valida(self): ok = False if hasattr(self, 'arxiu') and self.arxiu.filePath() == '': self.msgInfo("S'ha de seleccionar un arxiu de dades") self.arxiu.setFocus() elif self.zona.currentIndex() <= 0: self.msgInfo("S'ha de seleccionar una zona") self.zona.setFocus() elif self.capa.text().strip() == '': self.msgInfo("S'ha de introduir un nom de capa") self.capa.setFocus() elif self.tipus.currentIndex() <= 0: self.msgInfo("S'ha de seleccionar un tipus d'agregació") self.tipus.setFocus() elif self.calcul.currentText().strip() == '' and self.tipus.currentText() != 'Recompte': self.msgInfo("S'ha de introduir un cálcul per fer l'agregació") self.calcul.setFocus() elif self.fCSV is None: return self.msgInfo("No hi ha cap fitxer seleccionat") elif not self.validaSortida(self.capa.text().strip()): self.capa.setFocus() else: ok = True return ok def setRenderParams(self): self.renderParams = QvMapRendererParams(self.mapa.currentText()) if self.simple: self.renderParams.colorBase = mv.MAP_COLORS[self.renderParams.colorBase] else: self.renderParams.colorBase = mv.MAP_COLORS[self.color.currentText()] if self.renderParams.colorContorn is None or self.renderParams.colorContorn == 'Base': self.renderParams.colorContorn = self.renderParams.colorBase else: self.renderParams.colorContorn = mv.MAP_CONTORNS[self.renderParams.colorContorn] if self.tipus.currentText().startswith('Recompte') and \ self.distribucio.currentText() == "Total": self.renderParams.numDecimals = 0 else: self.renderParams.numDecimals = 2 if self.renderParams.tipusMapa == 'Àrees': self.renderParams.modeCategories = mv.MAP_METODES[self.metode.currentText()] self.renderParams.numCategories = self.intervals.value() if self.renderParams.tipusMapa == 'Cercles': zona = self.zona.currentText() if zona == 'Districte': self.renderParams.increase = 8 elif zona == 'Barri': self.renderParams.increase = 4 elif zona == 'Àrea estadística bàsica': self.renderParams.increase = 3 elif zona == 'Secció censal': self.renderParams.increase = 2 else: self.renderParams.increase = 1 def procesa(self): if self.taulaMostra is not None: self.taulaMostra.hide() self.setRenderParams() ok = self.fCSV.agregacio(self.llegenda, self.capa.text().strip(), self.zona.currentText(), self.tipus.currentText(), self.renderParams, campAgregat=self.calcul.currentText().strip(), simple=self.simple, filtre=self.filtre.currentText().strip(), tipusDistribucio=self.distribucio.currentText(), form=self) if ok: return '' else: return self.fCSV.msgError
class DistrictSettingsDialog(QDialog): """ A dialog used for plugin settings """ def __init__(self, parent=None): # pylint: disable=too-many-statements super().__init__(parent) self.setWindowTitle(self.tr('Redistrict Plugin | Settings')) layout = QVBoxLayout() self.auth_label = QLabel(self.tr('Authentication configuration')) layout.addWidget(self.auth_label) self.auth_value = QgsAuthConfigSelect() layout.addWidget(self.auth_value) auth_id = get_auth_config_id() if auth_id: self.auth_value.setConfigId(auth_id) layout.addWidget(QLabel(self.tr('API base URL'))) self.base_url_edit = QLineEdit() self.base_url_edit.setText(QgsSettings().value('redistrict/base_url', '', str, QgsSettings.Plugins)) layout.addWidget(self.base_url_edit) h_layout = QHBoxLayout() h_layout.addWidget(QLabel(self.tr('Check for completed requests every'))) self.check_every_spin = QSpinBox() self.check_every_spin.setMinimum(10) self.check_every_spin.setMaximum(600) self.check_every_spin.setSuffix(' ' + self.tr('s')) self.check_every_spin.setValue(QgsSettings().value('redistrict/check_every', '30', int, QgsSettings.Plugins)) h_layout.addWidget(self.check_every_spin) layout.addLayout(h_layout) self.use_mock_checkbox = QCheckBox(self.tr('Use mock Statistics NZ API')) self.use_mock_checkbox.setChecked(get_use_mock_api()) layout.addWidget(self.use_mock_checkbox) self.test_button = QPushButton(self.tr('Test API connection')) self.test_button.clicked.connect(self.test_api) layout.addWidget(self.test_button) self.use_overlays_checkbox = QCheckBox(self.tr('Show updated populations during interactive redistricting')) self.use_overlays_checkbox.setChecked( QgsSettings().value('redistrict/show_overlays', False, bool, QgsSettings.Plugins)) layout.addWidget(self.use_overlays_checkbox) self.use_sound_group_box = QGroupBox(self.tr('Use audio feedback')) self.use_sound_group_box.setCheckable(True) self.use_sound_group_box.setChecked( QgsSettings().value('redistrict/use_audio_feedback', False, bool, QgsSettings.Plugins)) sound_layout = QGridLayout() sound_layout.addWidget(QLabel(self.tr('When meshblock redistricted')), 0, 0) self.on_redistrict_file_widget = QgsFileWidget() self.on_redistrict_file_widget.setDialogTitle(self.tr('Select Audio File')) self.on_redistrict_file_widget.setStorageMode(QgsFileWidget.GetFile) self.on_redistrict_file_widget.setFilePath( QgsSettings().value('redistrict/on_redistrict', '', str, QgsSettings.Plugins)) self.on_redistrict_file_widget.setFilter(self.tr('Wave files (*.wav *.WAV)')) sound_layout.addWidget(self.on_redistrict_file_widget, 0, 1) self.play_on_redistrict_sound_button = QPushButton(self.tr('Test')) self.play_on_redistrict_sound_button.clicked.connect(self.play_on_redistrict_sound) sound_layout.addWidget(self.play_on_redistrict_sound_button, 0, 2) self.use_sound_group_box.setLayout(sound_layout) layout.addWidget(self.use_sound_group_box) button_box = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) layout.addWidget(button_box) button_box.rejected.connect(self.reject) button_box.accepted.connect(self.accept) self.setLayout(layout) def accept(self): # pylint: disable=missing-docstring super().accept() QgsSettings().setValue('redistrict/auth_config_id', self.auth_value.configId(), QgsSettings.Plugins) QgsSettings().setValue('redistrict/use_mock_api', self.use_mock_checkbox.isChecked(), QgsSettings.Plugins) QgsSettings().setValue('redistrict/base_url', self.base_url_edit.text(), QgsSettings.Plugins) QgsSettings().setValue('redistrict/check_every', self.check_every_spin.value(), QgsSettings.Plugins) QgsSettings().setValue('redistrict/show_overlays', self.use_overlays_checkbox.isChecked(), QgsSettings.Plugins) QgsSettings().setValue('redistrict/use_audio_feedback', self.use_sound_group_box.isChecked(), QgsSettings.Plugins) QgsSettings().setValue('redistrict/on_redistrict', self.on_redistrict_file_widget.filePath(), QgsSettings.Plugins) def test_api(self): """ Tests the API connection (real or mock!) """ connector = get_api_connector(use_mock=self.use_mock_checkbox.isChecked(), authcfg=self.auth_value.configId(), base_url=self.base_url_edit.text()) if connector.check(): QMessageBox.information(self, self.tr('Test API Connection'), self.tr('API responded OK!'), QMessageBox.Ok) else: QMessageBox.critical(self, self.tr('Test API Connection'), self.tr('Could not connect to API!'), QMessageBox.Ok) def play_on_redistrict_sound(self): """ Plays the 'on redistrict' sound """ try: playsound(self.on_redistrict_file_widget.filePath(), block=False) except FileNotFoundError: pass
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(433, 261) self.groupBox = QtWidgets.QGroupBox(Dialog) self.groupBox.setGeometry(QtCore.QRect(10, 10, 411, 241)) self.groupBox.setAutoFillBackground(True) self.groupBox.setTitle("") self.groupBox.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) self.groupBox.setFlat(False) self.groupBox.setCheckable(False) self.groupBox.setObjectName("groupBox") self.panImage = QgsFileWidget(self.groupBox) self.panImage.setGeometry(QtCore.QRect(210, 50, 171, 27)) self.panImage.setAccessibleName("") self.panImage.setObjectName("panImage") self.multImage = QgsFileWidget(self.groupBox) self.multImage.setEnabled(True) self.multImage.setGeometry(QtCore.QRect(210, 100, 171, 27)) self.multImage.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu) self.multImage.setLayoutDirection(QtCore.Qt.LeftToRight) self.multImage.setFileWidgetButtonVisible(True) self.multImage.setFullUrl(True) self.multImage.setFilter("") self.multImage.setDefaultRoot("") self.multImage.setObjectName("multImage") self.panImageLabel = QtWidgets.QLabel(self.groupBox) self.panImageLabel.setGeometry(QtCore.QRect(30, 50, 161, 20)) self.panImageLabel.setObjectName("panImageLabel") self.multImageLabel = QtWidgets.QLabel(self.groupBox) self.multImageLabel.setEnabled(True) self.multImageLabel.setGeometry(QtCore.QRect(30, 100, 161, 20)) self.multImageLabel.setAcceptDrops(False) self.multImageLabel.setFrameShape(QtWidgets.QFrame.NoFrame) self.multImageLabel.setFrameShadow(QtWidgets.QFrame.Plain) self.multImageLabel.setLineWidth(1) self.multImageLabel.setWordWrap(False) self.multImageLabel.setObjectName("multImageLabel") self.btnPansharpen = QtWidgets.QPushButton(self.groupBox) self.btnPansharpen.setGeometry(QtCore.QRect(230, 160, 91, 31)) self.btnPansharpen.setTabletTracking(False) self.btnPansharpen.setObjectName("btnPansharpen") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Qgis Pansharpen Plugin")) self.panImage.setDialogTitle(_translate("Dialog", "arquivo")) self.multImage.setDialogTitle(_translate("Dialog", "arquivo")) self.panImageLabel.setText( _translate("Dialog", "Panchromatic Image (.tiff)")) self.multImageLabel.setText( _translate("Dialog", "Multispectral Image (.tiff)")) self.btnPansharpen.setText(_translate("Dialog", "Pansharpen")) def panImageFile(self): return self.panImage.filePath() def multImageFile(self): return self.multImage.filePath() def GdalClass(self): return gdalClass.GdalClass() def onClick(self): print('botão funcionou') print(self.panImageFile()) print(self.multImageFile()) self.GdalClass().testando() nameOutput = os.path.basename( self.panImageFile()) + '-' + os.path.basename( self.multImageFile()) + '.tiff' output = os.path.join(os.path.dirname(self.panImageFile()), nameOutput) print(output) self.GdalClass().pansharpening(self.panImageFile(), self.multImageFile(), output)