예제 #1
0
    def _csmapToFile(self, dem, layer_set, outdir):

        if dem.rasterUnitsPerPixelX() == dem.rasterUnitsPerPixelY():
            dx = dem.rasterUnitsPerPixelX()
            dy = dem.rasterUnitsPerPixelY()
            w = dem.dataProvider().xSize()
            h = dem.dataProvider().ySize()
        elif dem.rasterUnitsPerPixelX() > dem.rasterUnitsPerPixelY():
            dx = dem.rasterUnitsPerPixelY()
            dy = dem.rasterUnitsPerPixelY()
            w = int(dem.dataProvider().xSize() *
                    (dem.rasterUnitsPerPixelX() / dem.rasterUnitsPerPixelY()))
            h = dem.dataProvider().ySize()
        else:
            dx = dem.rasterUnitsPerPixelX()
            dy = dem.rasterUnitsPerPixelX()
            w = dem.dataProvider().xSize()
            h = int(dem.dataProvider().ySize() *
                    (dem.rasterUnitsPerPixelY() / dem.rasterUnitsPerPixelX()))

        img = QtGui.QImage(QtCore.QSize(w, h),
                           QtGui.QImage.Format_ARGB32_Premultiplied)
        color = QtGui.QColor(255, 255, 255)
        img.fill(color.rgb())

        setting = QgsMapSettings()
        setting.setExtent(dem.dataProvider().extent())
        setting.setDestinationCrs(dem.crs())
        setting.setOutputSize(QtCore.QSize(w, h))
        setting.setLayers(layer_set)
        setting.updateDerived()

        p = QtGui.QPainter()
        p.begin(img)

        render = QgsMapRendererCustomPainterJob(setting, p)

        render.start()
        render.waitForFinished()

        p.end()

        temp = tempfile.NamedTemporaryFile()
        img.save(temp.name + ".tif", "tif")

        src_ds = gdal.Open(temp.name + ".tif")
        driver = gdal.GetDriverByName("GTiff")

        filepath, filename = os.path.split(
            str(dem.dataProvider().dataSourceUri()))

        dst_file = outdir + r"/csmap_" + filename
        dst_ds = driver.CreateCopy(dst_file, src_ds, 0)
        geo_trans = [
            dem.dataProvider().extent().xMinimum(), dx, 0,
            dem.dataProvider().extent().yMaximum(), 0, dy * -1
        ]
        dst_ds.SetGeoTransform(geo_trans)
        dst_ds.SetProjection(str(dem.crs().toWkt()))

        dst_ds = None
        src_ds = None
        temp.close()

        self.result_files.append(dst_file)
예제 #2
0
    def add_action(self,
                   icon_path,
                   text,
                   callback,
                   enabled_flag=True,
                   add_to_menu=True,
                   add_to_toolbar=True,
                   status_tip=None,
                   whats_this=None,
                   parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QtGui.QIcon(icon_path)

        try:
            from qgis.PyQt.QtGui import QAction
        except:
            from qgis.PyQt.QtWidgets import QAction

        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
예제 #3
0
    def accept(self):
        """Handler for when OK is clicked."""
        input_path = self.input_path.text()
        input_title = self.line_edit_title.text()
        input_source = self.line_edit_source.text()
        output_path = self.output_path.text()
        if not output_path.endswith('.tif'):
            # noinspection PyArgumentList,PyCallByClass,PyTypeChecker
            QMessageBox.warning(
                self,
                tr('InaSAFE'),
                tr('Output file name must be tif file'))
        if not os.path.exists(input_path):
            # noinspection PyArgumentList,PyCallByClass,PyTypeChecker
            QMessageBox.warning(
                self,
                tr('InaSAFE'),
                tr('Input file does not exist'))
            return

        algorithm = 'nearest'
        if self.nearest_mode.isChecked():
            algorithm = 'nearest'
        elif self.inverse_distance_mode.isChecked():
            algorithm = 'invdist'
        elif self.use_ascii_mode.isChecked():
            algorithm = 'use_ascii'

        # Smoothing
        smoothing_method = NONE_SMOOTHING
        if self.numpy_smoothing.isChecked():
            smoothing_method = NUMPY_SMOOTHING
        if self.scipy_smoothing.isChecked():
            smoothing_method = SCIPY_SMOOTHING

        # noinspection PyUnresolvedReferences
        QgsApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor)
        )

        extra_keywords = {}
        if self.check_box_custom_shakemap_id.isChecked():
            event_id = self.line_edit_shakemap_id.text()
            extra_keywords[extra_keyword_earthquake_event_id['key']] = event_id

        current_index = self.combo_box_source_type.currentIndex()
        source_type = self.combo_box_source_type.itemData(current_index)
        if source_type:
            extra_keywords[
                extra_keyword_earthquake_source['key']] = source_type

        file_name = convert_mmi_data(
            input_path,
            input_title,
            input_source,
            output_path,
            algorithm=algorithm,
            algorithm_filename_flag=True,
            smoothing_method=smoothing_method,
            extra_keywords=extra_keywords
        )

        file_info = QFileInfo(file_name)
        base_name = file_info.baseName()
        self.output_layer = QgsRasterLayer(file_name, base_name)

        # noinspection PyUnresolvedReferences
        QgsApplication.instance().restoreOverrideCursor()

        if self.load_result.isChecked():
            # noinspection PyTypeChecker
            mmi_ramp_roman(self.output_layer)
            self.output_layer.saveDefaultStyle()
            if not self.output_layer.isValid():
                LOGGER.debug("Failed to load")
            else:
                # noinspection PyArgumentList
                QgsProject.instance().addMapLayer(self.output_layer)
                iface.zoomToActiveLayer()

        if (self.keyword_wizard_checkbox.isChecked()
                and self.keyword_wizard_checkbox.isEnabled()):
            self.launch_keyword_wizard()

        self.done(self.Accepted)
예제 #4
0
    def __init__(self, parent=None, iface=None):
        """Constructor for import dialog.

        :param parent: Optional widget to use as parent.
        :type parent: QWidget

        :param iface: An instance of QgisInterface.
        :type iface: QgisInterface
        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)
        icon = resources_path('img', 'icons', 'show-osm-download.svg')
        self.setWindowIcon(QtGui.QIcon(icon))
        title = self.tr('InaSAFE OpenStreetMap Downloader')
        self.setWindowTitle(title)

        self.iface = iface
        self.progress_dialog = None

        # Set up things for context help
        self.help_button = self.button_box.button(
            QtWidgets.QDialogButtonBox.Help)
        # Allow toggling the help button
        self.help_button.setCheckable(True)
        self.help_button.toggled.connect(self.help_toggled)
        self.main_stacked_widget.setCurrentIndex(1)

        # Output directory
        self.directory_button.clicked.connect(self.directory_button_clicked)
        self.output_directory.setPlaceholderText(
            self.tr('[Create a temporary layer]'))

        # Disable boundaries group box until boundary checkbox is ticked
        self.boundary_group.setEnabled(False)

        # set up the validator for the file name prefix
        expression = QRegExp('^[A-Za-z0-9-_]*$')
        validator = QtGui.QRegExpValidator(expression, self.filename_prefix)
        self.filename_prefix.setValidator(validator)

        # Advanced panel
        self.line_edit_custom.setPlaceholderText(STAGING_SERVER)
        developer_mode = setting('developer_mode', expected_type=bool)
        self.group_box_advanced.setVisible(developer_mode)

        self.restore_state()

        # Setup the rectangle map tool
        self.canvas = iface.mapCanvas()
        self.rectangle_map_tool = \
            RectangleMapTool(self.canvas)
        self.rectangle_map_tool.rectangle_created.connect(
            self.update_extent_from_rectangle)
        self.capture_button.clicked.connect(
            self.drag_rectangle_on_map_canvas)

        # Setup pan tool
        self.pan_tool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.pan_tool)

        # Setup helper for admin_level
        json_file_path = resources_path('osm', 'admin_level_per_country.json')
        if os.path.isfile(json_file_path):
            with open(json_file_path, encoding='utf-8') as f:
                self.countries = json.load(f)
                self.bbox_countries = None
                self.populate_countries()
                # connect
                self.country_comboBox.currentIndexChanged.connect(
                    self.update_helper_political_level)
                self.admin_level_comboBox.currentIndexChanged.connect(
                    self.update_helper_political_level)

        self.update_extent_from_map_canvas()
예제 #5
0
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
import glob
import os
import re

from qgis.PyQt import QtCore, QtGui, QtWidgets

from qpals.qpals import QpalsShowFile
from qpals.qpals.QpalsModuleBase import QpalsModuleBase, QpalsRunBatch, ModuleLoadWorker, ModuleRunWorker
from qpals.qpals.qt_extensions.QpalsListWidgetItem import QpalsListWidgetItem

qtwhite = QtGui.QColor(255, 255, 255)
qtsoftred = QtGui.QColor(255, 140, 140)



def apply_backspace(s):
    while True:
        # if you find a character followed by a backspace, remove both
        t = re.sub('.\b', '', s, count=1)
        if len(s) == len(t):
            # now remove any backspaces from beginning of string
            return re.sub('\b+', '', t)
        s = t

def get_percentage(s):
    t = re.compile(r"(\d+)%")
예제 #6
0
 def getIcon(self):
     filepath = os.path.dirname(__file__) + "/../../../images/tool.png"
     return QtGui.QIcon(filepath)
예제 #7
0
#symbol = QgsLineSymbol.createSimple({'linestyle': 'dash', 'color': 'red'})
#layer.renderer().setSymbol(symbol)
#layer.triggerRepaint()

layer = QgsVectorLayer(fn, 'name', 'ogr')

tf1 = 'DIRECTION'
rangeList = []
opacity = 1

minVal = 0.0
maxVal = 2.0

lab = 'Group 1'

color1 = QtGui.QColor('#ffee00')

symbol = QgsSymbol.defaultSymbol(layer.geometryType())
symbol.setColor(color1)
symbol.setOpacity(opacity)

range1 = QgsRendererRange(minVal, maxVal, symbol, lab)
rangeList.append(range1)
#####
minVal = 2.1
maxVal = 4

lab = 'Group 2'

color2 = QtGui.QColor('#00eeff')
예제 #8
0
 def mark_current_profile_as_pending(self):
     """Mark the current profile as pending by colouring the text red.
     """
     index = self.profile_combo.currentIndex()
     item = self.profile_combo.model().item(index)
     item.setForeground(QtGui.QColor('red'))
예제 #9
0
 def mark_current_profile_as_saved(self):
     """Mark the current profile as saved by colouring the text black.
     """
     index = self.profile_combo.currentIndex()
     item = self.profile_combo.model().item(index)
     item.setForeground(QtGui.QColor('black'))
예제 #10
0
    def on_classifyPushButton_clicked(self):

        input_raster_layer_name = self.rasterLayerComboBox.currentText()
        input_vector_layer_name = self.vectorLayerComboBox.currentText()

        # 调用QGIS区域统计工具

        processing.run(
            'qgis:zonalstatistics', {
                'INPUT_RASTER': input_raster_layer_name,
                'RASTER_BAND': 1,
                'INPUT_VECTOR': input_vector_layer_name,
                'COLUMN_PREFIX': 'Band1_',
                'STATS': 2
            })
        processing.run(
            'qgis:zonalstatistics', {
                'INPUT_RASTER': input_raster_layer_name,
                'RASTER_BAND': 2,
                'INPUT_VECTOR': input_vector_layer_name,
                'COLUMN_PREFIX': 'Band2_',
                'STATS': 2
            })
        processing.run(
            'qgis:zonalstatistics', {
                'INPUT_RASTER': input_raster_layer_name,
                'RASTER_BAND': 3,
                'INPUT_VECTOR': input_vector_layer_name,
                'COLUMN_PREFIX': 'Band3_',
                'STATS': 2
            })
        # QgsProject.instance().addMapLayer(vector_layer)

        # 获取计算结果

        input_vector_layer = QgsProject.instance().mapLayersByName(
            input_vector_layer_name)[0]

        features = input_vector_layer.getFeatures()
        feature_id_list = []
        feature_band_list = []
        for feature in features:
            feature_id_list.append(feature.id())
            feature_band_list.append([
                feature['Band1_mean'], feature['Band2_mean'],
                feature['Band3_mean']
            ])

        # 聚类

        cluster_num = self.spinBox.value()
        cluster_result = cluster(np.array(feature_band_list))

        # 添加聚类结果到字段,字段存在则删除。只要涉及字段操作,每次操作都要更新字段

        field_name_list = [
            field.name() for field in input_vector_layer.fields()
        ]
        if 'cluster_id' in field_name_list:
            input_vector_layer.dataProvider().deleteAttributes(
                [field_name_list.index('cluster_id')])
            input_vector_layer.updateFields()

        input_vector_layer.dataProvider().addAttributes(
            [QgsField("cluster_id", QVariant.Int)])
        input_vector_layer.updateFields()
        field_name_list = [
            field.name() for field in input_vector_layer.fields()
        ]
        print(field_name_list)
        cluster_id_field_index = field_name_list.index('cluster_id')

        for index, fid in enumerate(feature_id_list):
            attrs = {cluster_id_field_index: int(cluster_result[index])}
            change_result = input_vector_layer.dataProvider(
            ).changeAttributeValues({fid: attrs})
            print(fid)
            print(attrs)
            print(change_result)
        input_vector_layer.updateFields()

        # 符号化

        categorized_renderer = QgsCategorizedSymbolRenderer()
        categorized_renderer.setClassAttribute('cluster_id')

        for cluster_id in range(cluster_num):
            fill_symbol = QgsFillSymbol.createSimple({})
            fill_symbol.setColor(
                QtGui.QColor(*np.random.randint(0, 256, 3), 200))
            categorized_renderer.addCategory(
                QgsRendererCategory(cluster_id, fill_symbol,
                                    f'cluster {cluster_id}'))
        input_vector_layer.setRenderer(categorized_renderer)
예제 #11
0
    def on_cannyPushButton_clicked(self):

        raster_layer_name = self.rasterLayerComboBox.currentText()
        raster_layer = QgsProject.instance().mapLayersByName(
            raster_layer_name)[0]
        provider = raster_layer.dataProvider()

        extent = provider.extent()
        rows = raster_layer.height()
        cols = raster_layer.width()

        # 读取栅格值

        block = provider.block(1, extent, cols, rows)
        img = np.zeros([rows, cols, 3], np.uint8)

        band_num = 3
        for band_index in range(band_num):
            block = provider.block(band_index + 1, extent, cols, rows)
            # for row_index in range(rows):
            #     for col_index in range(cols):
            #         img[row_index][col_index][band_index] = block.value(
            #             row_index, col_index)
            img[:, :,
                band_index] = np.array(block.data()).reshape([rows, cols])

        print(img)
        print(img.shape)

        edges = cv2.Canny(img, 200, 400, 15)
        plt.subplot(121)
        plt.imshow(img)
        plt.title('Original Image')
        plt.xticks([])
        plt.yticks([])
        plt.subplot(122)
        plt.imshow(edges, cmap='gray')
        plt.title('Edge Image')
        plt.xticks([])
        plt.yticks([])
        plt.show()
        cv2.imwrite(r'edge_result.jpg', edges)

        # 写入Tiff

        driver = gdal.GetDriverByName('GTiff')

        # 创建图像
        print(f'cols {cols}, rows {rows}')
        ds = driver.Create('edge_result.tif',
                           xsize=cols,
                           ysize=rows,
                           bands=1,
                           eType=gdal.GDT_Byte)
        # 设置参考坐标系
        crs_wkt = raster_layer.crs().toWkt()
        ds.SetProjection(crs_wkt)
        print(crs_wkt)

        # srs = osr.SpatialReference()
        # srs.SetUTM(12, 1)
        # srs.SetWellKnownGeogCS('WGS84')
        # ds.SetProjection(srs.ExportToWkt())

        # 设置Tiff的图像转换参数
        transformParam = [
            extent.xMinimum(), (extent.width() / cols), 0,
            extent.yMaximum(), 0, -(extent.height() / rows)
        ]
        ds.SetGeoTransform(transformParam)
        print(transformParam)
        # 写入数据
        ds.GetRasterBand(1).WriteArray(edges[:, :])
        # 关闭文件
        ds = None

        # 添加至图层并设置样式

        rlayer = QgsRasterLayer('edge_result.tif', "result tif layer")
        QgsProject.instance().addMapLayer(rlayer)

        palette_raster_render = QgsPalettedRasterRenderer(
            rlayer.dataProvider(), 1, [
                QgsPalettedRasterRenderer.Class(0, QtGui.QColor(0, 0, 0, 0)),
                QgsPalettedRasterRenderer.Class(255,
                                                QtGui.QColor(255, 0, 0, 255))
            ])
        rlayer.setRenderer(palette_raster_render)
예제 #12
0
    def setupUi(self, DbSettingsDialogBase):
        DbSettingsDialogBase.setObjectName(_fromUtf8("DbSettingsDialogBase"))
        DbSettingsDialogBase.resize(285, 166)
        self.layoutWidget = QtGui.QWidget(DbSettingsDialogBase)
        self.layoutWidget.setGeometry(QtCore.QRect(10, 10, 261, 141))
        self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.label_5 = QtGui.QLabel(self.layoutWidget)
        self.label_5.setObjectName(_fromUtf8("label_5"))
        self.gridLayout.addWidget(self.label_5, 0, 0, 1, 1)
        self.dbCombo = QtGui.QComboBox(self.layoutWidget)
        self.dbCombo.setObjectName(_fromUtf8("dbCombo"))
        self.gridLayout.addWidget(self.dbCombo, 0, 1, 1, 1)
        self.label_6 = QtGui.QLabel(self.layoutWidget)
        self.label_6.setObjectName(_fromUtf8("label_6"))
        self.gridLayout.addWidget(self.label_6, 1, 0, 1, 1)
        self.schemaCombo = QtGui.QComboBox(self.layoutWidget)
        self.schemaCombo.setObjectName(_fromUtf8("schemaCombo"))
        self.gridLayout.addWidget(self.schemaCombo, 1, 1, 1, 1)
        self.label_7 = QtGui.QLabel(self.layoutWidget)
        self.label_7.setObjectName(_fromUtf8("label_7"))
        self.gridLayout.addWidget(self.label_7, 2, 0, 1, 1)
        self.nameLineEdit = QtGui.QLineEdit(self.layoutWidget)
        self.nameLineEdit.setText(_fromUtf8(""))
        self.nameLineEdit.setObjectName(_fromUtf8("nameLineEdit"))
        self.gridLayout.addWidget(self.nameLineEdit, 2, 1, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        spacerItem = QtGui.QSpacerItem(18, 20, QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.okButton = QtGui.QPushButton(self.layoutWidget)
        self.okButton.setObjectName(_fromUtf8("okButton"))
        self.horizontalLayout.addWidget(self.okButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.retranslateUi(DbSettingsDialogBase)
        QtCore.QMetaObject.connectSlotsByName(DbSettingsDialogBase)
예제 #13
0
 def enable_busy_cursor(self):
     """Set the hourglass enabled."""
     QgsApplication.instance().setOverrideCursor(
         QtGui.QCursor(QtCore.Qt.WaitCursor))
예제 #14
0
 def setMask(self):
     """
     REGEx closely related to the valid chars method 'setValidCharacters'
     """
     if self.scaleCombo.currentText() == '1000k':
         regex = QtCore.QRegExp('[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}')
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '500k':
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}')
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '250k':
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}\-[A-Da-d]{1}')
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '100k':
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}\-[A-Da-d]{1}\-[IViv]{1,3}'
         )
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '50k':
         self.inomLineEdit.setInputMask('NN-NN-N-N-Nnn-0')
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}\-[A-Da-d]{1}\-[IViv]{1,3}\-[1-4]{1}'
         )
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '25k':
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}\-[A-Da-d]{1}\-[IViv]{1,3}\-[1-4]{1}\-[NSns]{1}[OEoe]{1}'
         )
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '10k':
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}\-[A-Da-d]{1}\-[IViv]{1,3}\-[1-4]{1}\-[NSns]{1}[OEoe]{1}\-[A-Fa-f]{1}'
         )
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '5k':
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}\-[A-Da-d]{1}\-[IViv]{1,3}\-[1-4]{1}\-[NSns]{1}[OEoe]{1}\-[A-Fa-f]{1}\-[IViv]{1,3}'
         )
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '2k':
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}\-[A-Da-d]{1}\-[IViv]{1,3}\-[1-4]{1}\-[NSns]{1}[OEoe]{1}\-[A-Fa-f]{1}\-[IViv]{1,3}\-[1-6]{1}'
         )
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
     elif self.scaleCombo.currentText() == '1k':
         regex = QtCore.QRegExp(
             '[NSns]{1}[A-Za-z]{1}\-[0-9]{1,2}\-[V-Zv-z]{1}\-[A-Da-d]{1}\-[IViv]{1,3}\-[1-4]{1}\-[NSns]{1}[OEoe]{1}\-[A-Fa-f]{1}\-[IViv]{1,3}\-[1-6]{1}\-[A-Da-d]{1}'
         )
         validator = QtGui.QRegExpValidator(regex, self.inomLineEdit)
         self.inomLineEdit.setValidator(validator)
예제 #15
0
 def paintEvent(self, event):
     painter = QtGui.QPainter(self)
     painter.drawImage(event.rect(), self.image)
     del painter
예제 #16
0
    def __init__(self, parent=None, dock=None):
        """Constructor for the minimum needs dialog.

        :param parent: Parent widget of this dialog.
        :type parent: QWidget

        :param dock: Dock widget instance that we can notify of changes.
        :type dock: Dock
        """
        QtWidgets.QDialog.__init__(self, parent)
        # List of parameters with the translated name.
        self.resource_parameters = {
            'Resource name': tr('Resource name'),
            'Resource description': tr('Resource description'),
            'Unit': tr('Unit'),
            'Units': tr('Units'),
            'Unit abbreviation': tr('Unit abbreviation'),
            'Minimum allowed': tr('Minimum allowed'),
            'Maximum allowed': tr('Maximum allowed'),
            'Default': tr('Default'),
            'Frequency': tr('Frequency'),
            'Readable sentence': tr('Readable sentence')
        }

        self.setupUi(self)
        icon = resources_path('img', 'icons', 'show-minimum-needs.svg')
        self.setWindowIcon(QtGui.QIcon(icon))
        self.dock = dock
        # These are in the little button bar at the bottom
        # 'Remove resource' button
        # noinspection PyUnresolvedReferences
        self.remove_resource_button.clicked.connect(self.remove_resource)
        self.remove_resource_button.setIcon(
            QIcon(os.path.join(resources_path(), 'img', 'icons',
                               'remove.svg')))

        # Add resource
        # noinspection PyUnresolvedReferences
        self.add_resource_button.clicked.connect(self.add_new_resource)
        self.add_resource_button.setIcon(
            QIcon(os.path.join(resources_path(), 'img', 'icons', 'add.svg')))
        # Edit resource
        # noinspection PyUnresolvedReferences
        self.edit_resource_button.clicked.connect(self.edit_resource)
        self.edit_resource_button.setIcon(
            QIcon(os.path.join(resources_path(), 'img', 'icons', 'edit.svg')))

        # Discard changes to a resource
        self.discard_changes_button = QPushButton(self.tr('Discard changes'))
        self.button_box.addButton(self.discard_changes_button,
                                  QDialogButtonBox.ActionRole)
        # noinspection PyUnresolvedReferences
        self.discard_changes_button.clicked.connect(self.discard_changes)

        # Restore defaults profiles
        self.restore_defaults_button = QPushButton(self.tr('Restore defaults'))
        self.button_box.addButton(self.restore_defaults_button,
                                  QDialogButtonBox.ActionRole)
        # noinspection PyUnresolvedReferences
        self.restore_defaults_button.clicked.connect(self.restore_defaults)

        # Save changes to a resource
        self.save_resource_button = QPushButton(self.tr('Save resource'))
        self.button_box.addButton(self.save_resource_button,
                                  QDialogButtonBox.ActionRole)
        # noinspection PyUnresolvedReferences
        self.save_resource_button.clicked.connect(self.save_resource)

        # Export profile button
        self.export_profile_button = QPushButton(self.tr('Export ...'))
        self.button_box.addButton(self.export_profile_button,
                                  QDialogButtonBox.ActionRole)
        # noinspection PyUnresolvedReferences
        self.export_profile_button.clicked.connect(self.export_profile)

        # Import profile button
        self.import_profile_button = QPushButton(self.tr('Import ...'))
        self.button_box.addButton(self.import_profile_button,
                                  QDialogButtonBox.ActionRole)
        # noinspection PyUnresolvedReferences
        self.import_profile_button.clicked.connect(self.import_profile)

        # New profile button
        self.new_profile_button = QPushButton(self.tr('New'))
        self.button_box.addButton(self.new_profile_button,
                                  QDialogButtonBox.ActionRole)
        # noinspection PyUnresolvedReferences
        self.new_profile_button.clicked.connect(self.new_profile)

        # Save profile button
        self.save_profile_button = QPushButton(self.tr('Save'))
        self.button_box.addButton(self.save_profile_button,
                                  QDialogButtonBox.ActionRole)
        # noinspection PyUnresolvedReferences
        self.save_profile_button.clicked.connect(self.save_profile)

        # 'Save as' profile button
        self.save_profile_as_button = QPushButton(self.tr('Save as'))
        self.button_box.addButton(self.save_profile_as_button,
                                  QDialogButtonBox.ActionRole)
        # noinspection PyUnresolvedReferences
        self.save_profile_as_button.clicked.connect(self.save_profile_as)

        # Set up things for context help
        self.help_button = self.button_box.button(
            QtWidgets.QDialogButtonBox.Help)
        # Allow toggling the help button
        self.help_button.setCheckable(True)
        self.help_button.toggled.connect(self.help_toggled)
        self.main_stacked_widget.setCurrentIndex(1)

        self.minimum_needs = NeedsProfile()
        self.edit_item = None

        # Remove profile button
        # noinspection PyUnresolvedReferences
        self.remove_profile_button.clicked.connect(self.remove_profile)

        # These are all buttons that will get hidden on context change
        # to the profile editing view
        self.profile_editing_buttons = list()
        self.profile_editing_buttons.append(self.remove_resource_button)
        self.profile_editing_buttons.append(self.add_resource_button)
        self.profile_editing_buttons.append(self.edit_resource_button)
        self.profile_editing_buttons.append(self.export_profile_button)
        self.profile_editing_buttons.append(self.import_profile_button)
        self.profile_editing_buttons.append(self.new_profile_button)
        self.profile_editing_buttons.append(self.save_profile_button)
        self.profile_editing_buttons.append(self.save_profile_as_button)
        # We also keep a list of all widgets to disable in context of resource
        # editing (not hidden, just disabled)
        self.profile_editing_widgets = self.profile_editing_buttons
        self.profile_editing_widgets.append(self.remove_profile_button)
        self.profile_editing_widgets.append(self.profile_combo)
        # These are all buttons that will get hidden on context change
        # to the resource editing view
        self.resource_editing_buttons = list()
        self.resource_editing_buttons.append(self.discard_changes_button)
        self.resource_editing_buttons.append(self.save_resource_button)
        for item in self.resource_editing_buttons:
            item.hide()

        self.load_profiles()
        # Next 2 lines fixes issues #1388 #1389 #1390 #1391
        if self.profile_combo.count() > 0:
            self.select_profile(0)

        # initial sync profile_combo and resource list
        self.clear_resource_list()
        self.populate_resource_list()
        self.set_up_resource_parameters()
        # Only do this afterward load_profiles to avoid the resource list
        # being updated
        # noinspection PyUnresolvedReferences
        self.profile_combo.activated.connect(self.select_profile)
        # noinspection PyUnresolvedReferences
        self.stacked_widget.currentChanged.connect(self.page_changed)
        self.select_profile(self.profile_combo.currentIndex())
예제 #17
0
 def showEvent(self, event):
     newImage = QtGui.QImage(self.size(), QtGui.QImage.Format_RGB32)
     newImage.fill(QtGui.qRgb(255, 255, 255))
     self.image = newImage
     self.render_userimage()
 def icon(self):
     return QtGui.QIcon(":/plugins/qgis_geonode/mIconGeonode.svg")
    def __init__(self, parent, orgslist, in_distribution=False):
        super(InlineContactWidget, self).__init__(parent)
        self.parent = parent
        self.superParent = parent.superParent
        self.setupUi(self)
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)

        self.orgs = {}
        org = orgslist
        for x in org:
            name = org[x] + " (" + x + ")"
            self.orgs[x] = customCombo.CodeListItem(name, name, name)

        self.combo_org.setModel(
            customCombo.CustomComboBoxModel(
                self, [customCombo.CodeListItem(OUTRA, OUTRA, OUTRA)] +
                sorted(list(self.orgs.values()), key=lambda x: x.term_pt)))
        self.combo_org.currentIndexChanged.connect(self.check_org)

        # initialized where because if was on the spot the c++ garbage collector will destroy it and cause a error
        self.dialog = None
        tla.setupListView(self.phone, QgsFilterLineEdit, self, NoParent=True)
        tla.setupListView(self.email, QgsFilterLineEdit, self, NoParent=True)
        tla.setupListView(self.fax, QgsFilterLineEdit, self, NoParent=True)

        tla.setupMandatoryField(None, self.organization,
                                self.label_organization,
                                tla.formatTooltip(u"Elemento Obrigatório."))
        tla.setupMandatoryField(
            None, self.email, self.label_email,
            tla.formatTooltip(
                u"Deve ser indicado pelo menos um endereço eletrónico (\'<em>email</em>\')."
            ))

        for btn in self.findChildren(qwidgets.QPushButton,
                                     qcore.QRegExp('btn_*')):
            if '_add_' in btn.objectName():
                btn.setIcon(
                    qgui.QIcon(':/resourcesFolder/icons/plus_icon.svg'))
                btn.setText('')
            elif '_del_' in btn.objectName():
                btn.setIcon(
                    qgui.QIcon(':/resourcesFolder/icons/delete_icon.svg'))
                btn.setText('')
        for info in self.findChildren(qwidgets.QPushButton,
                                      qcore.QRegExp('info_*')):
            info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg'))
            info.setText('')
            info.pressed.connect(self.printHelp)
        f = open(
            os.path.join(pluginDirectory('EditorMetadadosMarswInforbiomares'),
                         'resourcesFolder/stylesheet.qtcss'))
        self.sytlesheet = f.read()
        for btn in self.findChildren(qwidgets.QPushButton):
            btn.setStyleSheet(self.sytlesheet)
            btn.setFocusPolicy(Qt.NoFocus)
        self.name.editingFinished.connect(self.updateTitle)
        self.organization.textChanged.connect(self.updateTitle)
        self.city.editingFinished.connect(self.updateTitle)
        self.country.editingFinished.connect(self.updateTitle)
        self.email.model().dataChanged.connect(self.updateTitle)
        self.btn_del_contact.clicked.connect(self.deleteContact)
        self.btn_contact_list.clicked.connect(self.importFromListContacts)
        self.btn_addto_list_contacts.clicked.connect(self.addtoListOfContacts)
        self.mGroupBox.collapsedStateChanged.connect(self.hideButtons)
        self.btn_del_contact.setToolTip(tla.formatTooltip(u"Agagar contacto."))
        self.updateTitle()

        self.btn_addto_list_contacts.setIcon(
            qgui.QIcon(':/resourcesFolder/icons/save_icon.svg'))
        self.btn_addto_list_contacts.setToolTip(
            tla.formatTooltip(u"Guardar contacto na Lista de Contactos."))
        self.btn_contact_list.setIcon(
            qgui.QIcon(':/resourcesFolder/icons/contactsList_icon.svg'))
        self.btn_contact_list.setToolTip(u'Importar da Lista de Contactos')
        self.btn_contact_list.setText('')
        self.btn_addto_list_contacts.setText('')
        self.eater = tla.EatWheel()
        for x in self.findChildren(qwidgets.QComboBox):
            x.installEventFilter(self.eater)
            x.setFocusPolicy(Qt.StrongFocus)
        for x in self.findChildren(QDateTimeEdit):
            x.installEventFilter(self.eater)
            x.setFocusPolicy(Qt.StrongFocus)
        for x in self.findChildren(QDateEdit):
            x.installEventFilter(self.eater)
            x.setFocusPolicy(Qt.StrongFocus)

        if in_distribution:
            temp = {}
            temp["distributor"] = {}
            temp["distributor"]["en"] = "distributor"
            temp["distributor"]["pt"] = "Distribuidor"
            temp["distributor"]["description"] = "Distribuidor"

            self.roles = customCombo.dic_to_CustomComboBox_dic(temp)
            self.combo_role.setModel(
                customCombo.CustomComboBoxModel(
                    self,
                    sorted(list(self.roles.values()),
                           key=lambda x: x.term_pt)))
            self.combo_role.setDisabled(True)
        else:
            self.roles = customCombo.dic_to_CustomComboBox_dic(
                self.superParent.codelist["CI_RoleCode"])
            self.combo_role.setModel(
                customCombo.CustomComboBoxModel(
                    self,
                    sorted(list(self.roles.values()),
                           key=lambda x: x.term_pt)))
            tla.setupMandatoryField(
                None, self.combo_role, self.label_role,
                u"Tem que ser especificada uma função para o contacto.")
            self.combo_role.currentIndexChanged.connect(
                self.check_mandatory_completude)
예제 #20
0
    def __init__(self,
                 canvas=None,
                 atributs=None,
                 canviCapaActiva=None,
                 editable=True):
        qgGui.QgsLayerTreeView.__init__(self)

        self.setWindowTitle('Llegenda')
        self.project = qgCor.QgsProject.instance()
        self.root = self.project.layerTreeRoot()
        self.canvas = None
        self.bridge = None
        self.bridges = []
        self.atributs = atributs
        self.editable = True
        self.lastExtent = None
        self.escales = None
        self.directory = '.'
        self.mask = None
        self.removing = False
        # self.restoreExtent = 0
        # print('restoreExtent', self.restoreExtent)

        self.project.readProject.connect(self.nouProjecte)
        self.project.legendLayersAdded.connect(self.actIcones)
        self.root.layerOrderChanged.connect(self.actIcones)
        # self.project.loadingLayerMessageReceived.connect(self.msgCapes)

        # self.setWhatsThis(QvApp().carregaAjuda(self))

        # Asociar canvas y bridges
        self.mapBridge(canvas)

        # Evento de nueva capa seleccionada
        self.connectaCanviCapaActiva(canviCapaActiva)

        # Model
        self.model = QvModelLlegenda(self.root)
        self.model.setFlag(qgCor.QgsLegendModel.ShowLegend, True)
        self.model.setFlag(qgCor.QgsLegendModel.ShowLegendAsTree, True)
        self.editarLlegenda(editable)

        self.setModel(self.model)
        if self.canvas is not None:
            self.canvas.scaleChanged.connect(self.connectaEscala)

        # Acciones disponibles
        self.accions = QvAccions()
        self.setAccions()
        # Lista de acciones que apareceran en el menú
        self.menuAccions = []
        self.setMenuProvider(QvMenuLlegenda(self))

        self.iconaFiltre = qgGui.QgsLayerTreeViewIndicator()
        self.iconaFiltre.setIcon(
            qtGui.QIcon(os.path.join(imatgesDir, 'filter.png')))
        self.iconaFiltre.setToolTip('Filtre actiu')
        self.iconaFiltre.clicked.connect(self.filterElements)

        self.iconaMap = qgGui.QgsLayerTreeViewIndicator()
        self.iconaMap.setIcon(
            qtGui.QIcon(os.path.join(imatgesDir, 'categories2.png')))
        self.iconaMap.setToolTip('Categories de mapificació')
        self.iconaMap.clicked.connect(
            lambda: QvFormSimbMapificacio.executa(self))

        if self.atributs is not None:
            self.atributs.modificatFiltreCapa.connect(self.actIconaFiltre)

        self.projecteCapes = None
        self.player = None

        if self.canvas is not None:
            self.escales = QvEscala(self.canvas)
            self.project.layerLoaded.connect(self.iniProjecte)
            self.canvas.layersChanged.connect(self.capesProject)
            self.canvas.renderStarting.connect(self.fiProjecte)
            # self.canvas.renderComplete.connect(self.fiProjecte)

        self.fSignal = lambda: self.projecteModificat.emit(
            'canvasLayersChanged')
        self.iniSignal = False
예제 #21
0
    def setupUi(self, enhanceWindow):
        enhanceWindow.setObjectName("enhanceWindow")
        enhanceWindow.resize(1070, 750)
        self.centralwidget = QtWidgets.QWidget(enhanceWindow)
        self.centralwidget.setObjectName("centralwidget")
        #self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView = graphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QtCore.QRect(150, 40, 881, 561))
        self.graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.graphicsView.setObjectName("graphicsView")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(50, 30, 61, 16))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(50, 80, 71, 16))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(50, 130, 61, 16))
        self.label_3.setObjectName("label_3")
        self.spinBoxRed = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBoxRed.setGeometry(QtCore.QRect(50, 270, 61, 22))
        self.spinBoxRed.setMinimum(-100)
        self.spinBoxRed.setMaximum(100)
        self.spinBoxRed.setSingleStep(5)
        self.spinBoxRed.setObjectName("spinBoxRed")
        self.spinBoxGreen = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBoxGreen.setGeometry(QtCore.QRect(50, 330, 61, 22))
        self.spinBoxGreen.setMinimum(-100)
        self.spinBoxGreen.setMaximum(100)
        self.spinBoxGreen.setSingleStep(5)
        self.spinBoxGreen.setObjectName("spinBoxGreen")
        self.spinBoxBlue = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBoxBlue.setGeometry(QtCore.QRect(50, 390, 61, 22))
        self.spinBoxBlue.setMinimum(-100)
        self.spinBoxBlue.setMaximum(100)
        self.spinBoxBlue.setSingleStep(5)
        self.spinBoxBlue.setObjectName("spinBoxBlue")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(50, 180, 47, 13))
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(50, 250, 47, 13))
        self.label_5.setObjectName("label_5")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(50, 310, 47, 13))
        self.label_6.setObjectName("label_6")
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(50, 370, 47, 13))
        self.label_7.setObjectName("label_7")
        self.buttonBoxReset = QtWidgets.QDialogButtonBox(self.centralwidget)
        self.buttonBoxReset.setGeometry(QtCore.QRect(40, 550, 81, 23))
        self.buttonBoxReset.setStandardButtons(QtWidgets.QDialogButtonBox.Reset)
        self.buttonBoxReset.setObjectName("buttonBoxReset")
        self.applyButton = QtWidgets.QPushButton(self.centralwidget)
        self.applyButton.setGeometry(QtCore.QRect(860, 630, 71, 23))
        self.applyButton.setObjectName("applyButton")
        self.spinBoxContrast = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBoxContrast.setGeometry(QtCore.QRect(50, 50, 62, 22))
        self.spinBoxContrast.setMinimum(-100)
        self.spinBoxContrast.setMaximum(100)
        self.spinBoxContrast.setSingleStep(5)
        self.spinBoxContrast.setObjectName("spinBoxContrast")
        self.spinBoxLuminosite = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBoxLuminosite.setGeometry(QtCore.QRect(50, 100, 62, 22))
        self.spinBoxLuminosite.setMinimum(-100)
        self.spinBoxLuminosite.setMaximum(100)
        self.spinBoxLuminosite.setSingleStep(5)
        self.spinBoxLuminosite.setObjectName("spinBoxLuminosite")
        self.spinBoxSaturation = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBoxSaturation.setGeometry(QtCore.QRect(50, 150, 62, 22))
        self.spinBoxSaturation.setMinimum(-100)
        self.spinBoxSaturation.setMaximum(100)
        self.spinBoxSaturation.setSingleStep(5)
        self.spinBoxSaturation.setObjectName("spinBoxSaturation")
        self.spinBoxNettete = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBoxNettete.setGeometry(QtCore.QRect(50, 200, 62, 22))
        self.spinBoxNettete.setMinimum(-100)
        self.spinBoxNettete.setMaximum(100)
        self.spinBoxNettete.setSingleStep(5)
        self.spinBoxNettete.setObjectName("spinBoxNettete")
        self.zoomInButton = QtWidgets.QPushButton(self.centralwidget)
        self.zoomInButton.setEnabled(False)
        self.zoomInButton.setGeometry(QtCore.QRect(160, 620, 30, 30))
        self.zoomInButton.setStyleSheet("background-color:rgba(200, 200, 200);")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/Anaglyph/Icons/zoomIn.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.zoomInButton.setIcon(icon)
        self.zoomInButton.setIconSize(QtCore.QSize(30, 30))
        self.zoomInButton.setObjectName("zoomInButton")
        self.zoomOutButton = QtWidgets.QPushButton(self.centralwidget)
        self.zoomOutButton.setEnabled(False)
        self.zoomOutButton.setGeometry(QtCore.QRect(200, 620, 30, 30))
        self.zoomOutButton.setStyleSheet("background-color:rgba(200, 200, 200);")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/Anaglyph/Icons/zoomOut.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.zoomOutButton.setIcon(icon1)
        self.zoomOutButton.setIconSize(QtCore.QSize(30, 30))
        self.zoomOutButton.setObjectName("zoomOutButton")
        self.zoomPanButton = QtWidgets.QPushButton(self.centralwidget)
        self.zoomPanButton.setEnabled(False)
        self.zoomPanButton.setGeometry(QtCore.QRect(240, 620, 30, 30))
        self.zoomPanButton.setStyleSheet("background-color:rgba(200, 200, 200);")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(":/Anaglyph/Icons/panOption.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.zoomPanButton.setIcon(icon2)
        self.zoomPanButton.setIconSize(QtCore.QSize(30, 30))
        self.zoomPanButton.setCheckable(True)
        self.zoomPanButton.setObjectName("zoomPanButton")
        self.groupBoxMinMax = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBoxMinMax.setEnabled(True)
        self.groupBoxMinMax.setGeometry(QtCore.QRect(20, 435, 120, 101))
        self.groupBoxMinMax.setCheckable(True)
        self.groupBoxMinMax.setChecked(False)
        self.groupBoxMinMax.setObjectName("groupBoxMinMax")
        self.radioButtonComplete = QtWidgets.QRadioButton(self.groupBoxMinMax)
        self.radioButtonComplete.setEnabled(False)
        self.radioButtonComplete.setGeometry(QtCore.QRect(20, 25, 91, 17))
        self.radioButtonComplete.setChecked(True)
        self.radioButtonComplete.setObjectName("radioButtonComplete")
        self.radioButtonCurrent = QtWidgets.QRadioButton(self.groupBoxMinMax)
        self.radioButtonCurrent.setEnabled(False)
        self.radioButtonCurrent.setGeometry(QtCore.QRect(20, 50, 91, 17))
        self.radioButtonCurrent.setObjectName("radioButtonCurrent")
        self.currentStatusButton = QtWidgets.QPushButton(self.groupBoxMinMax)
        self.currentStatusButton.setEnabled(False)
        self.currentStatusButton.setGeometry(QtCore.QRect(20, 70, 75, 23))
        self.currentStatusButton.setObjectName("currentStatusButton")
        self.cancelButton = QtWidgets.QPushButton(self.centralwidget)
        self.cancelButton.setGeometry(QtCore.QRect(940, 630, 75, 23))
        self.cancelButton.setObjectName("cancelButton")
        self.groupBoxPicture = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBoxPicture.setGeometry(QtCore.QRect(30, 590, 81, 61))
        self.groupBoxPicture.setTitle("")
        self.groupBoxPicture.setObjectName("groupBoxPicture")
        self.radioButtonPremiere = QtWidgets.QRadioButton(self.groupBoxPicture)
        self.radioButtonPremiere.setGeometry(QtCore.QRect(10, 20, 82, 17))
        self.radioButtonPremiere.setChecked(True)
        self.radioButtonPremiere.setObjectName("radioButtonPremiere")
        self.radioButtonDeuxieme = QtWidgets.QRadioButton(self.groupBoxPicture)
        self.radioButtonDeuxieme.setGeometry(QtCore.QRect(10, 40, 82, 17))
        self.radioButtonDeuxieme.setObjectName("radioButtonDeuxieme")
        enhanceWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(enhanceWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1070, 21))
        self.menubar.setObjectName("menubar")
        enhanceWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(enhanceWindow)
        self.statusbar.setObjectName("statusbar")
        enhanceWindow.setStatusBar(self.statusbar)

        self.retranslateUi(enhanceWindow)
        QtCore.QMetaObject.connectSlotsByName(enhanceWindow)
    def setupUi(self, GBIFOccurrencesDialogBase):
        GBIFOccurrencesDialogBase.setObjectName(
            _fromUtf8("GBIFOccurrencesDialogBase"))
        GBIFOccurrencesDialogBase.resize(544, 662)
        self.progressBar = QtGui.QProgressBar(GBIFOccurrencesDialogBase)
        self.progressBar.setGeometry(QtCore.QRect(216, 610, 321, 31))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName(_fromUtf8("progressBar"))
        self.loadButton = QtGui.QPushButton(GBIFOccurrencesDialogBase)
        self.loadButton.setGeometry(QtCore.QRect(10, 611, 141, 30))
        self.loadButton.setCheckable(False)
        self.loadButton.setDefault(False)
        self.loadButton.setFlat(False)
        self.loadButton.setObjectName(_fromUtf8("loadButton"))
        self.loadingLabel = QtGui.QLabel(GBIFOccurrencesDialogBase)
        self.loadingLabel.setGeometry(QtCore.QRect(20, 600, 501, 20))
        self.loadingLabel.setText(_fromUtf8(""))
        self.loadingLabel.setObjectName(_fromUtf8("loadingLabel"))
        self.line = QtGui.QFrame(GBIFOccurrencesDialogBase)
        self.line.setGeometry(QtCore.QRect(10, 570, 511, 16))
        self.line.setFrameShape(QtGui.QFrame.HLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName(_fromUtf8("line"))
        self.label_4 = QtGui.QLabel(GBIFOccurrencesDialogBase)
        self.label_4.setGeometry(QtCore.QRect(30, 90, 62, 20))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Lucida Grande"))
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.layoutWidget = QtGui.QWidget(GBIFOccurrencesDialogBase)
        self.layoutWidget.setGeometry(QtCore.QRect(73, 130, 391, 408))
        self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
        self.gridLayout = QtGui.QGridLayout(self.layoutWidget)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.institutionCodeField = QtGui.QLineEdit(self.layoutWidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.institutionCodeField.sizePolicy().hasHeightForWidth())
        self.institutionCodeField.setSizePolicy(sizePolicy)
        self.institutionCodeField.setObjectName(
            _fromUtf8("institutionCodeField"))
        self.gridLayout.addWidget(self.institutionCodeField, 11, 1, 1, 1)
        self.datasetKeyField = QtGui.QLineEdit(self.layoutWidget)
        self.datasetKeyField.setObjectName(_fromUtf8("datasetKeyField"))
        self.gridLayout.addWidget(self.datasetKeyField, 15, 1, 1, 1)
        self.gridLayout_2 = QtGui.QGridLayout()
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
        self.yearRangeBox = QtGui.QCheckBox(self.layoutWidget)
        self.yearRangeBox.setObjectName(_fromUtf8("yearRangeBox"))
        self.gridLayout_2.addWidget(self.yearRangeBox, 0, 0, 1, 1)
        self.minYearEdit = QtGui.QLineEdit(self.layoutWidget)
        self.minYearEdit.setObjectName(_fromUtf8("minYearEdit"))
        self.gridLayout_2.addWidget(self.minYearEdit, 1, 0, 1, 1)
        self.maxYearEdit = QtGui.QLineEdit(self.layoutWidget)
        self.maxYearEdit.setEnabled(False)
        self.maxYearEdit.setObjectName(_fromUtf8("maxYearEdit"))
        self.gridLayout_2.addWidget(self.maxYearEdit, 1, 1, 1, 1)
        self.gridLayout.addLayout(self.gridLayout_2, 7, 1, 1, 1)
        self.taxonKeyField = QtGui.QLineEdit(self.layoutWidget)
        self.taxonKeyField.setObjectName(_fromUtf8("taxonKeyField"))
        self.gridLayout.addWidget(self.taxonKeyField, 2, 1, 1, 1)
        self.catalogNumberField = QtGui.QLineEdit(self.layoutWidget)
        self.catalogNumberField.setObjectName(_fromUtf8("catalogNumberField"))
        self.gridLayout.addWidget(self.catalogNumberField, 5, 1, 1, 1)
        self.label_13 = QtGui.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.label_13.setFont(font)
        self.label_13.setObjectName(_fromUtf8("label_13"))
        self.gridLayout.addWidget(self.label_13, 0, 0, 1, 2)
        self.label_8 = QtGui.QLabel(self.layoutWidget)
        self.label_8.setObjectName(_fromUtf8("label_8"))
        self.gridLayout.addWidget(self.label_8, 12, 0, 1, 1)
        self.label_10 = QtGui.QLabel(self.layoutWidget)
        self.label_10.setObjectName(_fromUtf8("label_10"))
        self.gridLayout.addWidget(self.label_10, 2, 0, 1, 1)
        self.label_3 = QtGui.QLabel(self.layoutWidget)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.gridLayout.addWidget(self.label_3, 4, 0, 1, 1)
        self.label_2 = QtGui.QLabel(self.layoutWidget)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1)
        self.recordedByField = QtGui.QLineEdit(self.layoutWidget)
        self.recordedByField.setObjectName(_fromUtf8("recordedByField"))
        self.gridLayout.addWidget(self.recordedByField, 6, 1, 1, 1)
        self.label_5 = QtGui.QLabel(self.layoutWidget)
        self.label_5.setObjectName(_fromUtf8("label_5"))
        self.gridLayout.addWidget(self.label_5, 5, 0, 1, 1)
        self.label_15 = QtGui.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.label_15.setFont(font)
        self.label_15.setObjectName(_fromUtf8("label_15"))
        self.gridLayout.addWidget(self.label_15, 8, 0, 1, 2)
        self.label_9 = QtGui.QLabel(self.layoutWidget)
        self.label_9.setObjectName(_fromUtf8("label_9"))
        self.gridLayout.addWidget(self.label_9, 7, 0, 1, 1)
        self.countryComboBox = QtGui.QComboBox(self.layoutWidget)
        self.countryComboBox.setObjectName(_fromUtf8("countryComboBox"))
        self.gridLayout.addWidget(self.countryComboBox, 4, 1, 1, 1)
        self.basisComboBox = QtGui.QComboBox(self.layoutWidget)
        self.basisComboBox.setObjectName(_fromUtf8("basisComboBox"))
        self.gridLayout.addWidget(self.basisComboBox, 3, 1, 1, 1)
        self.label = QtGui.QLabel(self.layoutWidget)
        self.label.setObjectName(_fromUtf8("label"))
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.scientificNameField = QtGui.QLineEdit(self.layoutWidget)
        self.scientificNameField.setObjectName(
            _fromUtf8("scientificNameField"))
        self.gridLayout.addWidget(self.scientificNameField, 1, 1, 1, 1)
        self.label_7 = QtGui.QLabel(self.layoutWidget)
        self.label_7.setObjectName(_fromUtf8("label_7"))
        self.gridLayout.addWidget(self.label_7, 11, 0, 1, 1)
        self.label_11 = QtGui.QLabel(self.layoutWidget)
        self.label_11.setObjectName(_fromUtf8("label_11"))
        self.gridLayout.addWidget(self.label_11, 15, 0, 1, 1)
        self.label_12 = QtGui.QLabel(self.layoutWidget)
        self.label_12.setObjectName(_fromUtf8("label_12"))
        self.gridLayout.addWidget(self.label_12, 6, 0, 1, 1)
        self.collectionCodeField = QtGui.QLineEdit(self.layoutWidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.collectionCodeField.sizePolicy().hasHeightForWidth())
        self.collectionCodeField.setSizePolicy(sizePolicy)
        self.collectionCodeField.setObjectName(
            _fromUtf8("collectionCodeField"))
        self.gridLayout.addWidget(self.collectionCodeField, 12, 1, 1, 1)
        self.publishingCountryComboBox = QtGui.QComboBox(self.layoutWidget)
        self.publishingCountryComboBox.setObjectName(
            _fromUtf8("publishingCountryComboBox"))
        self.gridLayout.addWidget(self.publishingCountryComboBox, 9, 1, 1, 1)
        self.label_6 = QtGui.QLabel(self.layoutWidget)
        self.label_6.setObjectName(_fromUtf8("label_6"))
        self.gridLayout.addWidget(self.label_6, 9, 0, 1, 1)
        self.stopButton = QtGui.QPushButton(GBIFOccurrencesDialogBase)
        self.stopButton.setEnabled(False)
        self.stopButton.setGeometry(QtCore.QRect(150, 611, 61, 31))
        self.stopButton.setObjectName(_fromUtf8("stopButton"))
        self.layoutWidget.raise_()
        self.progressBar.raise_()
        self.loadButton.raise_()
        self.loadingLabel.raise_()
        self.line.raise_()
        self.label_4.raise_()
        self.stopButton.raise_()

        self.retranslateUi(GBIFOccurrencesDialogBase)
        QtCore.QMetaObject.connectSlotsByName(GBIFOccurrencesDialogBase)
예제 #23
0
import os.path
import processing
from qgis.core import (QgsVectorLayer, QgsField, QgsFeatureIterator,
                       QgsVectorFileWriter, QgsProject, QgsLayerTreeLayer)
import glob
from qgis.PyQt.QtCore import QVariant
from qgis.PyQt import QtCore, QtGui, QtSql
import datetime
import csv
import posixpath
import ntpath
import shutil
from PyQt5.QtWidgets import QMessageBox

msgBox = QMessageBox()
msgBox.setWindowIcon(QtGui.QIcon(':/APEXMOD/pics/am_icon.png'))


def create_conv_runoff(self):
    APEXMOD_path_dict = self.dirs_and_paths()

    # Create apexmf_results tree inside
    root = QgsProject.instance().layerTreeRoot()
    if root.findGroup("APEX-MODFLOW"):
        SM = root.findGroup("APEX-MODFLOW")
        SM.insertGroup(0, "Scenarios")
        scenario_tree = root.findGroup("Scenarios")
        scenario_tree.addGroup("Pumping from MODFLOW")
        input1 = QgsProject.instance().mapLayersByName("sub (SWAT)")[0]

        # Copy sub shapefile to be under "p from mf"
    def __init__(self, parent, combos, coord=None):

        if not coord:
            coord = ["", None, "", None, None]
        super(FreeKeyWordsDialog, self).__init__(parent)
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)
        self.setupUi(self)
        self.date_date_2 = NullQDateEditWrapper(self.date_date_2)
        self.setModal(True)
        self.combo_dataType.setModel(
            CustomComboBoxModel(
                self, [None] +
                sorted(list(combos[1].values()), key=lambda x: x.term_pt)))
        self.combo_dataType.setCurrentIndex(0)
        self.date_date_2.clear()
        self.combo_type.setModel(
            CustomComboBoxModel(
                self, [None] +
                sorted(list(combos[0].values()), key=lambda x: x.term_pt)))
        self.btn_cancelar.clicked.connect(lambda: self.done(QDialog.Rejected))
        self.line_keyword.textChanged.connect(lambda: self.check_fields())
        self.line_thesaurus.textChanged.connect(lambda: self.check_fields())
        self.combo_type.currentIndexChanged.connect(
            lambda: self.check_fields())
        self.combo_dataType.currentIndexChanged.connect(
            lambda: self.check_fields())
        self.date_date_2.get_original().dateTimeChanged.connect(
            lambda: self.check_fields())
        self.btn_adicionar.clicked.connect(lambda: self.done(QDialog.Accepted))
        self.btn_adicionar.setDisabled(True)
        self.combo_type.setDisabled(True)
        self.line_thesaurus.setDisabled(True)
        self.date_date_2.setDisabled(True)
        self.btn_clear_date_date_2.setDisabled(True)
        self.combo_dataType.setDisabled(True)

        self.line_keyword.setText(coord[0])
        if coord[1] is not None:
            buf = combos[0].get(coord[1].term_pt, None)
            if buf is not None:
                self.combo_type.setCurrentIndex(
                    self.combo_type.findText(buf.term_pt))
        self.line_thesaurus.setText(coord[2])
        if coord[3] is None:
            self.date_date_2.clear()
        else:
            self.date_date_2.setDate(coord[3])
        if coord[4] is not None:
            buf = combos[1].get(coord[4].term, None)
            if buf is not None:
                self.combo_dataType.setCurrentIndex(
                    self.combo_dataType.findText(buf.term_pt))
        self.superParent = None
        temp = self.parent()
        while self.superParent is None:
            if issubclass(type(temp), keywordsPanel.Ui_keywords):
                self.superParent = temp
            else:
                temp = temp.parent()

        for info in self.findChildren(qwidgets.QPushButton, QRegExp('info_*')):
            info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg'))
            info.setText('')
            info.pressed.connect(self.printHelp)

        self.btn_clear_date_date_2.setIcon(
            qgui.QIcon(':/resourcesFolder/icons/delete_field.svg'))
        self.btn_clear_date_date_2.pressed.connect(
            lambda: self.date_date_2.clear())
예제 #25
0
class moduleSelector(QtWidgets.QDialog):

    IconPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "media")
    opalsIcon = QtGui.QIcon(os.path.join(IconPath, "opalsIcon.png"))
    cmdIcon = QtGui.QIcon(os.path.join(IconPath, "cmd_icon.png"))
    loadingIcon = QtGui.QIcon(os.path.join(IconPath, "spinner_icon.png"))
    errorIcon = QtGui.QIcon(os.path.join(IconPath, "error_icon.png"))
    checkIcon = QtGui.QIcon(os.path.join(IconPath, "opalsIconCheck.png"))

    abort_signal = QtCore.pyqtSignal(name='abort_signal')

    def getModulesAvailiable(self):
        for opalsexe in glob.glob(os.path.join(self.project.opalspath, "opals*.exe")):
            self.modulesAvailiable.append({'name': os.path.basename(opalsexe).split(".exe")[0],
                                           'icon': self.opalsIcon,
                                           'class': QpalsModuleBase(opalsexe,self.project, layerlist=self.layerlist)})
        self.modulesAvailiable.append({'name': "User-defined cmd", 'icon': self.cmdIcon, 'class': QpalsRunBatch()})


    def __init__(self, iface, layerlist, project):
        super(moduleSelector, self).__init__(None)#, QtCore.Qt.WindowStaysOnTopHint)
        self.project = project
        self.iface = iface
        self.layerlist = layerlist
        self.curmodule=None
        self.modulesAvailiable = []

        self.getModulesAvailiable()
        self.initUi()
        self.resize(1200, 600)
        self.workerrunning = False
        self.threads = []
        self.workers = []
        self.runningRunList = False
        self.currentruncount = 0

        self.runModuleSelected = None


    def initUi(self):

        groupSelect = QtWidgets.QGroupBox()
        self.moduleList = QtWidgets.QListWidget()
        for moduleDict in self.modulesAvailiable:
            module = QpalsListWidgetItem(moduleDict)
            module.paramClass.listitem = module
            self.moduleList.addItem(module)
        self.moduleList.itemClicked.connect(self.loadModuleAsync)

        filterBox = QtWidgets.QHBoxLayout()
        filterBox.addWidget(QtWidgets.QLabel("Filter:"))
        self.filterText = QtWidgets.QLineEdit()
        self.filterText.textChanged.connect(self.filterModuleList)
        filterBox.addWidget(self.filterText, stretch=1)
        filterClear = QtWidgets.QPushButton()
        filterClear.setText("X")
        filterClear.setMaximumWidth(20)
        filterClear.pressed.connect(self.clearFilterText)
        filterBox.addWidget(filterClear)
        self.loadAllBtn = QtWidgets.QPushButton()
        self.loadAllBtn.setText("load all")
        self.loadAllBtn.pressed.connect(self.loadAllModules)
        filterBox.addWidget(self.loadAllBtn)

        groupSelect.setTitle("Module Selector")
        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.moduleList, stretch=1)
        vbox.addLayout(filterBox)
        groupSelect.setLayout(vbox)

        self.moduleparamLayout = QtWidgets.QVBoxLayout()

        self.moduleparamBox = QtWidgets.QGroupBox()
        self.moduleparamBox.setTitle("Module parameters")
        self.moduleparamBox.setLayout(self.moduleparamLayout)

        rungroup = QtWidgets.QGroupBox()
        rungroup.setTitle("Run list")
        self.runListWidget = QtWidgets.QListWidget()
        #self.runListWidget.currentItemChanged.connect(self.loadModuleAsync)
        self.runListWidget.itemClicked.connect(self.loadModuleAsync)
        self.runListWidget.setDragEnabled(True)
        self.runListWidget.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)

        runAllBtn = QtWidgets.QPushButton()
        runAllBtn.setText("Run")
        runAllBtn.clicked.connect(self.runRunList)

        runDelZone = QpalsDeleteLabel("Drop here to remove")
        runDelZone.setAcceptDrops(True)

        runvbox = QtWidgets.QVBoxLayout()
        runvbox.addWidget(self.runListWidget, stretch=1)
        runhbox = QtWidgets.QHBoxLayout()
        runhbox.addWidget(runDelZone)
        runhbox.addWidget(runAllBtn)
        runvbox.addLayout(runhbox)
        saveloadbox = QtWidgets.QHBoxLayout()
        savbtn = QtWidgets.QPushButton("Save .bat")
        loadbtn = QtWidgets.QPushButton("Load .bat")
        savbtn.clicked.connect(self.saveRunList)
        loadbtn.clicked.connect(self.loadRunList)
        saveloadbox.addWidget(savbtn)
        saveloadbox.addWidget(loadbtn)

        self.pbar = QtWidgets.QProgressBar()
        self.pbar.setValue(100)
        runvbox.addWidget(self.pbar)
        runvbox.addLayout(saveloadbox)
        rungroup.setLayout(runvbox)

        grpBoxContainer = QtWidgets.QHBoxLayout()
        grpBoxContainer.addWidget(groupSelect)
        grpBoxContainer.addWidget(self.moduleparamBox, stretch=1)
        grpBoxContainer.addWidget(rungroup)

        lowerhbox = QtWidgets.QHBoxLayout()

        statusLayoutBox = QtWidgets.QHBoxLayout()
        self.statusText = QtWidgets.QTextEdit()
        self.statusText.setReadOnly(True)
        self.statusText.setVisible(False)
        self.progressBar = QtWidgets.QProgressBar()
        self.progressBar.setRange(0, 100)
        statusLayoutBox.addWidget(self.statusText, 1)

        self.statusBar = QtWidgets.QPushButton()
        self.statusBar.clicked.connect(self.showHideStatusText)
        self.statusBar.setFlat(True)
        self.statusBar.setStyleSheet("text-align:left")
        self.statusBar.setToolTip("Click to show/hide command line output")
        statusBarLayout = QtWidgets.QHBoxLayout()
        self.stopExec = QtWidgets.QPushButton()
        self.stopExec.setText("Stop")
        self.stopExec.clicked.connect(self.stop)
        statusBarLayout.addWidget(self.statusBar, 1)
        statusBarLayout.addWidget(self.progressBar)
        statusBarLayout.addWidget(self.stopExec)
        self.setWorkerRunning(False)

        overallBox = QtWidgets.QVBoxLayout()
        overallBox.addLayout(grpBoxContainer)
        overallBox.addLayout(lowerhbox)
        overallBox.addLayout(statusLayoutBox)
        overallBox.addLayout(statusBarLayout)

        self.main_widget = QtWidgets.QWidget()
        self.main_widget.setLayout(overallBox)
        self.setLayout(overallBox)
        self.setWindowTitle('qpals')

    def showHideStatusText(self):
        currstatus = self.statusText.isHidden()
        self.statusText.setHidden(not currstatus)

    def setWorkerRunning(self, status):
        self.workerrunning = status
        self.stopExec.setEnabled(status)
        self.progressBar.setValue(0)
        self.statusBar.setText("")

    def stop(self):
        if self.workerrunning:
            self.abort_signal.emit()
        self.setWorkerRunning(False)
        self.statusBar.setText("Stopped Execution.")
        self.progressBar.setValue(0)

    def filterModuleList(self, text):
        self.moduleList.clear()
        for moduleDict in self.modulesAvailiable:
            if text.lower() in moduleDict['name'].lower():
                module = QpalsListWidgetItem(moduleDict)
                module.paramClass.listitem = module
                self.moduleList.addItem(module)

    def startWorker(self, module):
        #https://snorfalorpagus.net/blog/2013/12/07/multithreading-in-qgis-python-plugins/
        if self.workerrunning:
            return
        self.setWorkerRunning(True)
        worker = ModuleLoadWorker(module)
        module.setIcon(self.loadingIcon)
        self.moduleList.setEnabled(False)
        # start the worker in a new thread
        thread = QtCore.QThread(self)
        worker.moveToThread(thread)
        worker.finished.connect(self.workerFinished)
        worker.error.connect(self.workerError)
        thread.started.connect(worker.run)
        thread.start()
        self.thread = thread
        self.worker = worker

    def workerFinished(self, ret):
        # clean up the worker and thread
        self.worker.deleteLater()
        self.thread.quit()
        self.thread.wait()
        self.thread.deleteLater()
        if ret is not None:
            # report the result
            module, code = ret
            module.setIcon(module.icon)
            self.loadModule(module)
        else:
            # notify the user that something went wrong
            self.iface.messageBar().pushMessage('Something went wrong! See the message log for more information.', duration=3)
        self.setWorkerRunning(False)
        self.moduleList.setEnabled(True)

    def workerError(self, e, exception_string, module):
        print('Worker thread raised an exception: {}\n'.format(exception_string))
        module.setIcon(self.errorIcon)
        self.setWorkerRunning(False)

    def loadModuleAsync(self, module):
        self.moduleList.clearSelection()
        self.runListWidget.clearSelection()
        self.runModuleSelected = module
        if module and isinstance(module.paramClass, QpalsModuleBase):
            if module.paramClass.loaded:
                self.loadModule(module)
                self.viewbox.setChecked(module.paramClass.visualize)
            else:
                self.startWorker(module)
        else:
            self.loadModule(module)  # display "select a module"

    def showHelp(self):
        if self.curmodule:
            import webbrowser
            webbrowser.open('file:///' + os.path.join(self.project.opalspath, "..", "doc", "html",
                                                      "Module" + self.curmodule.text()[5:] + ".html"))

    def loadModule(self, module):
        if module:  # can happen if it gets filtered away
            form = QtWidgets.QVBoxLayout()
            self.moduleparamBox.setTitle("Parameters for " + module.text())

            helpBtn = QtWidgets.QPushButton("Module help")
            helpBtn.clicked.connect(self.showHelp)

            parameterform = module.paramClass.getParamUi(parent=self)
            form.addLayout(parameterform, stretch=1)
            # reset / run / add to list / add to view
            resetbar = QtWidgets.QHBoxLayout()
            resetbtn = QtWidgets.QPushButton("Reset")
            resetbtn.clicked.connect(lambda: self.resetModule(module))
            runbtn = QtWidgets.QPushButton("Run now")
            runbtn.clicked.connect(lambda: self.runModuleAsync(module))
            addbtn = QtWidgets.QPushButton("Add to run list >")
            addbtn.clicked.connect(self.addToRunList)
            if "opals" in module.text():
                self.viewbox = QtWidgets.QCheckBox("Add result to canvas")
                self.viewbox.clicked.connect(self.viewboxChanged)
                self.commonbtn = QtWidgets.QPushButton("Common and Global parameters")
                self.commonwin = module.paramClass.getGlobalCommonParamsWindow(parent=self)
                self.commonbtn.clicked.connect(self.commonwin.show)
                form.addWidget(self.commonbtn)
            #viewbox.stateChanged.connect(module.paramClass.view = viewbox.isChecked())
            resetbar.addStretch(1)
            resetbar.addWidget(helpBtn)
            resetbar.addWidget(resetbtn)
            resetbar.addWidget(runbtn)
            resetbar.addWidget(addbtn)

            if "opals" in module.text():
                resetbar.addWidget(self.viewbox)
            #resetbar.addWidget(commonbtn)
            #resetbar.addWidget(globalbtn)
            form.addLayout(resetbar)
            module.paramClass.revalidate = True
            module.paramClass.validate()
            self.curmodule = module

        else:
            form = QtWidgets.QHBoxLayout()
            l1 = QtWidgets.QLabel("No module selected...")
            form.addWidget(l1)
            self.moduleparamBox.setTitle("Module Parameters")

        self.clearLayout(self.moduleparamLayout)
        self.moduleparamLayout.addLayout(form)

    def resetModule(self, module):
        module.paramClass.reset()
        module.setBackgroundColor(qtwhite)
        self.clearLayout(self.moduleparamLayout)
        self.loadModule(module)

    def clearFilterText(self):
        self.filterText.setText("")

    def clearLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.clearLayout(item.layout())

    def loadAllModules(self):
        for module_id in range(self.moduleList.count()-1):
            module = self.moduleList.item(module_id)
            try:
                module.paramClass.load()
            except Exception as e:
                print(e)
        self.loadAllBtn.hide()

    def viewboxChanged(self):
        self.curmodule.paramClass.visualize = self.viewbox.isChecked()

    def addToRunList(self):
        import copy
        modulecopy = copy.deepcopy(self.curmodule)
        self.runListWidget.addItem(modulecopy)
        modulecopy.paramClass.revalidate = True
        self.resetModule(self.curmodule)

    def runModuleAsync(self, module):
        worker = ModuleRunWorker(module)
        thread = QtCore.QThread(self)
        worker.moveToThread(thread)
        worker.finished.connect(self.runModuleWorkerFinished)
        worker.error.connect(self.runModuleWorkerError)
        worker.status.connect(self.workerStatus)
        self.abort_signal.connect(worker.stop)
        thread.started.connect(worker.run)
        self.setWorkerRunning(True)
        thread.start()
        self.threads.append(thread)
        self.workers.append(worker)


    def workerStatus(self, message):
        curtext = message.replace("\r", "").replace("\b", "")  # eliminate carriage returns and backspaces
        self.statusText.setPlainText(curtext)
        self.statusText.verticalScrollBar().setValue(self.statusText.verticalScrollBar().maximum())

        out_lines = ["Stage 0: Initializing"] + [item for item in re.split("[\n\r\b]", message) if item]
        curr_stage = [stage for stage in out_lines if "Stage" in stage][-1]
        percentage = out_lines[-1]
        #print percentage
        if r"%" in percentage:
            perc = get_percentage(percentage)
            self.progressBar.setValue(int(perc))
            statusbartext = curr_stage
        else:
            statusbartext = out_lines[-1]

        self.statusBar.setText(statusbartext)


    def runModuleWorkerFinished(self, ret):
        err, errmsg, module = ret
        moduleClass = module.paramClass
        if moduleClass.visualize and moduleClass.outf:
            if not os.path.isabs(moduleClass.outf):
                moduleClass.outf = os.path.join(self.project.workdir, moduleClass.outf).replace("\\", "/")
            showfile = QpalsShowFile.QpalsShowFile(self.project.iface, self.layerlist, self.project)
            showfile.load(infile_s=[moduleClass.outf])
        self.setWorkerRunning(False)
        if self.runningRunList == True:
            module.setIcon(self.checkIcon)
            self.currentruncount += 1
            self.runRunList()

    def runModuleWorkerError(self, e, message, module):
        pass

    def runRunList(self):
        self.runningRunList = True
        self.pbar.setValue(int(100*self.currentruncount/self.runListWidget.count()))
        if self.runListWidget.count() > self.currentruncount:
            self.runModuleAsync(self.runListWidget.item(self.currentruncount))
        else:
            self.runningRunList = False
            self.currentruncount = 0

    def saveRunList(self):
        saveTo = QtWidgets.QFileDialog.getSaveFileName(None, caption='Save to file')
        if True:
            f = open(saveTo, 'w')
            f.write("rem BATCH FILE CREATED WITH QPALS\r\n")
            for i in range(self.runListWidget.count()):
                item = self.runListWidget.item(i)
                module = item.paramClass
                f.write(str(module) + "\r\n")
            f.close()

    def loadRunList(self):
        loadFrom = QtWidgets.QFileDialog.getOpenFileName(None, caption='Load from file')
        f = open(loadFrom, 'r')
        lines = f.readlines()
        skipnext = False
        for i in range(len(lines)):
            try:
                if not skipnext:
                    line = lines[i]
                    nextline = lines[i+1] if len(lines) > i+1 else ""
                    if line[0:3].lower() == "rem" or line.startswith("::"):
                        module = None
                    elif line.startswith("opals"):
                        ModuleBase = QpalsModuleBase.fromCallString(line, self.project, self.layerlist)
                        module = QpalsListWidgetItem({'name': line.split()[0].split(".exe")[0],
                                                   'icon': self.opalsIcon,
                                                   'class': ModuleBase})
                        ModuleBase.listitem = module
                    else:
                        if line.startswith("cd ") and not (nextline.startswith("rem")
                                                    or nextline.startswith("::")
                                                    or nextline.startswith("opals")):
                            chdir = line[3:].strip().strip("/D")
                            call = nextline.strip()
                            skipnext = True
                        else:
                            chdir = ""
                            call = line.strip()
                        module = QpalsListWidgetItem({'name': "User-defined cmd", 'icon': self.cmdIcon,
                                                      'class': QpalsRunBatch(call, chdir)})
                    if module:
                        self.runListWidget.addItem(module)
            except Exception as e:
                print(e)
예제 #26
0
 def getIcon(self):
     return QtGui.QIcon(os.path.dirname(__file__) + "/../images/wps.png")
예제 #27
0
    def setupUi(self, QgisCloudPlugin):
        QgisCloudPlugin.setObjectName("QgisCloudPlugin")
        QgisCloudPlugin.resize(501, 703)
        QgisCloudPlugin.setLocale(
            QtCore.QLocale(QtCore.QLocale.English,
                           QtCore.QLocale.UnitedStates))
        self.dockWidgetContents = QtWidgets.QWidget()
        self.dockWidgetContents.setObjectName("dockWidgetContents")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.dockWidgetContents)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.tabWidget = QtWidgets.QTabWidget(self.dockWidgetContents)
        self.tabWidget.setObjectName("tabWidget")
        self.mapTab = QtWidgets.QWidget()
        self.mapTab.setObjectName("mapTab")
        self.gridLayout_4 = QtWidgets.QGridLayout(self.mapTab)
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.logo_2 = QtWidgets.QLabel(self.mapTab)
        self.logo_2.setAutoFillBackground(False)
        self.logo_2.setPixmap(QtGui.QPixmap(":/plugins/qgiscloud/logo.png"))
        self.logo_2.setScaledContents(False)
        self.logo_2.setAlignment(QtCore.Qt.AlignCenter)
        self.logo_2.setObjectName("logo_2")
        self.gridLayout_4.addWidget(self.logo_2, 0, 0, 1, 1)
        self.btnBackgroundLayer = QtWidgets.QToolButton(self.mapTab)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnBackgroundLayer.sizePolicy().hasHeightForWidth())
        self.btnBackgroundLayer.setSizePolicy(sizePolicy)
        self.btnBackgroundLayer.setPopupMode(
            QtWidgets.QToolButton.InstantPopup)
        self.btnBackgroundLayer.setToolButtonStyle(
            QtCore.Qt.ToolButtonTextOnly)
        self.btnBackgroundLayer.setArrowType(QtCore.Qt.NoArrow)
        self.btnBackgroundLayer.setObjectName("btnBackgroundLayer")
        self.gridLayout_4.addWidget(self.btnBackgroundLayer, 1, 0, 1, 1)
        self.labelOpenLayersPlugin = QtWidgets.QLabel(self.mapTab)
        self.labelOpenLayersPlugin.setWordWrap(True)
        self.labelOpenLayersPlugin.setObjectName("labelOpenLayersPlugin")
        self.gridLayout_4.addWidget(self.labelOpenLayersPlugin, 2, 0, 1, 1)
        self.line_2 = QtWidgets.QFrame(self.mapTab)
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")
        self.gridLayout_4.addWidget(self.line_2, 3, 0, 1, 1)
        self.btnPublishMap = QtWidgets.QPushButton(self.mapTab)
        self.btnPublishMap.setObjectName("btnPublishMap")
        self.gridLayout_4.addWidget(self.btnPublishMap, 4, 0, 1, 1)
        self.line_3 = QtWidgets.QFrame(self.mapTab)
        self.line_3.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_3.setObjectName("line_3")
        self.gridLayout_4.addWidget(self.line_3, 5, 0, 1, 1)
        self.widgetServices = QtWidgets.QWidget(self.mapTab)
        self.widgetServices.setObjectName("widgetServices")
        self.gridLayout = QtWidgets.QGridLayout(self.widgetServices)
        self.gridLayout.setObjectName("gridLayout")
        self.label = QtWidgets.QLabel(self.widgetServices)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.lblWMS = QtWidgets.QLabel(self.widgetServices)
        self.lblWMS.setOpenExternalLinks(True)
        self.lblWMS.setObjectName("lblWMS")
        self.gridLayout.addWidget(self.lblWMS, 1, 1, 1, 1)
        self.label_5 = QtWidgets.QLabel(self.widgetServices)
        self.label_5.setObjectName("label_5")
        self.gridLayout.addWidget(self.label_5, 2, 0, 1, 1)
        self.lblMaps = QtWidgets.QLabel(self.widgetServices)
        self.lblMaps.setOpenExternalLinks(True)
        self.lblMaps.setObjectName("lblMaps")
        self.gridLayout.addWidget(self.lblMaps, 2, 1, 1, 1)
        self.label_8 = QtWidgets.QLabel(self.widgetServices)
        self.label_8.setObjectName("label_8")
        self.gridLayout.addWidget(self.label_8, 3, 0, 1, 1)
        self.lblMobileMap_2 = QtWidgets.QLabel(self.widgetServices)
        self.lblMobileMap_2.setEnabled(True)
        self.lblMobileMap_2.setOpenExternalLinks(True)
        self.lblMobileMap_2.setObjectName("lblMobileMap_2")
        self.gridLayout.addWidget(self.lblMobileMap_2, 3, 1, 1, 1)
        self.label_3 = QtWidgets.QLabel(self.widgetServices)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 0, 0, 1, 1)
        self.lblWebmap = QtWidgets.QLabel(self.widgetServices)
        self.lblWebmap.setOpenExternalLinks(True)
        self.lblWebmap.setObjectName("lblWebmap")
        self.gridLayout.addWidget(self.lblWebmap, 0, 1, 1, 1)
        self.gridLayout_4.addWidget(self.widgetServices, 6, 0, 1, 1)
        spacerItem = QtWidgets.QSpacerItem(20, 20,
                                           QtWidgets.QSizePolicy.Minimum,
                                           QtWidgets.QSizePolicy.Fixed)
        self.gridLayout_4.addItem(spacerItem, 7, 0, 1, 1)
        self.frame = QtWidgets.QFrame(self.mapTab)
        self.frame.setEnabled(True)
        self.frame.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setLineWidth(1)
        self.frame.setObjectName("frame")
        self.gridLayout_6 = QtWidgets.QGridLayout(self.frame)
        self.gridLayout_6.setObjectName("gridLayout_6")
        self.widgetMaps = QtWidgets.QWidget(self.frame)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetMaps.sizePolicy().hasHeightForWidth())
        self.widgetMaps.setSizePolicy(sizePolicy)
        self.widgetMaps.setObjectName("widgetMaps")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.widgetMaps)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.tabMaps = QtWidgets.QListWidget(self.widgetMaps)
        self.tabMaps.setObjectName("tabMaps")
        self.gridLayout_2.addWidget(self.tabMaps, 1, 0, 1, 4)
        self.btnMapDelete = QtWidgets.QPushButton(self.widgetMaps)
        self.btnMapDelete.setEnabled(False)
        self.btnMapDelete.setObjectName("btnMapDelete")
        self.gridLayout_2.addWidget(self.btnMapDelete, 2, 2, 1, 1)
        self.lblMaps_3 = QtWidgets.QLabel(self.widgetMaps)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.lblMaps_3.setFont(font)
        self.lblMaps_3.setObjectName("lblMaps_3")
        self.gridLayout_2.addWidget(self.lblMaps_3, 0, 0, 1, 1)
        spacerItem1 = QtWidgets.QSpacerItem(145, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.gridLayout_2.addItem(spacerItem1, 2, 3, 1, 1)
        self.btnMapLoad = QtWidgets.QPushButton(self.widgetMaps)
        self.btnMapLoad.setObjectName("btnMapLoad")
        self.gridLayout_2.addWidget(self.btnMapLoad, 2, 0, 1, 1)
        self.btnMapEdit = QtWidgets.QPushButton(self.widgetMaps)
        self.btnMapEdit.setObjectName("btnMapEdit")
        self.gridLayout_2.addWidget(self.btnMapEdit, 2, 1, 1, 1)
        self.gridLayout_6.addWidget(self.widgetMaps, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame, 8, 0, 1, 1)
        self.tabWidget.addTab(self.mapTab, "")
        self.uploadTab = QtWidgets.QWidget()
        self.uploadTab.setEnabled(True)
        self.uploadTab.setObjectName("uploadTab")
        self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.uploadTab)
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_10 = QtWidgets.QLabel(self.uploadTab)
        self.label_10.setObjectName("label_10")
        self.horizontalLayout_3.addWidget(self.label_10)
        self.cbUploadDatabase = QtWidgets.QComboBox(self.uploadTab)
        self.cbUploadDatabase.setObjectName("cbUploadDatabase")
        self.horizontalLayout_3.addWidget(self.cbUploadDatabase)
        self.verticalLayout_6.addLayout(self.horizontalLayout_3)
        self.lblDbSizeUpload = QtWidgets.QLabel(self.uploadTab)
        self.lblDbSizeUpload.setText("")
        self.lblDbSizeUpload.setObjectName("lblDbSizeUpload")
        self.verticalLayout_6.addWidget(self.lblDbSizeUpload)
        self.tblLocalLayers = QtWidgets.QTableWidget(self.uploadTab)
        self.tblLocalLayers.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectRows)
        self.tblLocalLayers.setObjectName("tblLocalLayers")
        self.tblLocalLayers.setColumnCount(0)
        self.tblLocalLayers.setRowCount(0)
        self.tblLocalLayers.horizontalHeader().setStretchLastSection(True)
        self.tblLocalLayers.verticalHeader().setVisible(False)
        self.verticalLayout_6.addWidget(self.tblLocalLayers)
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        spacerItem2 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_7.addItem(spacerItem2)
        self.btnRefreshLocalLayers = QtWidgets.QPushButton(self.uploadTab)
        self.btnRefreshLocalLayers.setObjectName("btnRefreshLocalLayers")
        self.horizontalLayout_7.addWidget(self.btnRefreshLocalLayers)
        self.verticalLayout_6.addLayout(self.horizontalLayout_7)
        self.btnUploadData = QtWidgets.QPushButton(self.uploadTab)
        self.btnUploadData.setObjectName("btnUploadData")
        self.verticalLayout_6.addWidget(self.btnUploadData)
        self.progressWidget = QtWidgets.QWidget(self.uploadTab)
        self.progressWidget.setObjectName("progressWidget")
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.progressWidget)
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.spinner = Spinner(self.progressWidget)
        self.spinner.setObjectName("spinner")
        self.horizontalLayout_6.addWidget(self.spinner)
        self.lblProgress = QtWidgets.QLabel(self.progressWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.lblProgress.sizePolicy().hasHeightForWidth())
        self.lblProgress.setSizePolicy(sizePolicy)
        self.lblProgress.setText("")
        self.lblProgress.setObjectName("lblProgress")
        self.horizontalLayout_6.addWidget(self.lblProgress)
        self.verticalLayout_6.addWidget(self.progressWidget)
        self.tabWidget.addTab(self.uploadTab, "")
        self.accountTab = QtWidgets.QWidget()
        self.accountTab.setObjectName("accountTab")
        self.gridLayout_5 = QtWidgets.QGridLayout(self.accountTab)
        self.gridLayout_5.setObjectName("gridLayout_5")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.label_2 = QtWidgets.QLabel(self.accountTab)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_4.addWidget(self.label_2)
        self.editServer = QtWidgets.QLineEdit(self.accountTab)
        self.editServer.setEnabled(True)
        self.editServer.setObjectName("editServer")
        self.horizontalLayout_4.addWidget(self.editServer)
        self.resetUrlBtn = QtWidgets.QToolButton(self.accountTab)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/plugins/qgiscloud/icon.png"),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.resetUrlBtn.setIcon(icon)
        self.resetUrlBtn.setObjectName("resetUrlBtn")
        self.horizontalLayout_4.addWidget(self.resetUrlBtn)
        self.gridLayout_5.addLayout(self.horizontalLayout_4, 0, 0, 1, 1)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.btnLogin = QtWidgets.QPushButton(self.accountTab)
        self.btnLogin.setObjectName("btnLogin")
        self.horizontalLayout_5.addWidget(self.btnLogin)
        self.lblSignup = QtWidgets.QLabel(self.accountTab)
        self.lblSignup.setAlignment(QtCore.Qt.AlignCenter)
        self.lblSignup.setOpenExternalLinks(True)
        self.lblSignup.setObjectName("lblSignup")
        self.horizontalLayout_5.addWidget(self.lblSignup)
        self.lblLoginStatus = QtWidgets.QLabel(self.accountTab)
        self.lblLoginStatus.setObjectName("lblLoginStatus")
        self.horizontalLayout_5.addWidget(self.lblLoginStatus)
        spacerItem3 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem3)
        self.btnLogout = QtWidgets.QPushButton(self.accountTab)
        self.btnLogout.setObjectName("btnLogout")
        self.horizontalLayout_5.addWidget(self.btnLogout)
        self.gridLayout_5.addLayout(self.horizontalLayout_5, 1, 0, 1, 1)
        self.widgetDatabases = QtWidgets.QWidget(self.accountTab)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetDatabases.sizePolicy().hasHeightForWidth())
        self.widgetDatabases.setSizePolicy(sizePolicy)
        self.widgetDatabases.setObjectName("widgetDatabases")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.widgetDatabases)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.line = QtWidgets.QFrame(self.widgetDatabases)
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.verticalLayout_3.addWidget(self.line)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_29 = QtWidgets.QLabel(self.widgetDatabases)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.label_29.setFont(font)
        self.label_29.setObjectName("label_29")
        self.horizontalLayout_2.addWidget(self.label_29)
        self.lblDbSize = QtWidgets.QLabel(self.widgetDatabases)
        self.lblDbSize.setText("")
        self.lblDbSize.setObjectName("lblDbSize")
        self.horizontalLayout_2.addWidget(self.lblDbSize)
        self.verticalLayout_3.addLayout(self.horizontalLayout_2)
        self.tabDatabases = QtWidgets.QListWidget(self.widgetDatabases)
        self.tabDatabases.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectRows)
        self.tabDatabases.setObjectName("tabDatabases")
        self.verticalLayout_3.addWidget(self.tabDatabases)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.btnDbCreate = QtWidgets.QPushButton(self.widgetDatabases)
        self.btnDbCreate.setObjectName("btnDbCreate")
        self.horizontalLayout.addWidget(self.btnDbCreate)
        self.btnDbDelete = QtWidgets.QPushButton(self.widgetDatabases)
        self.btnDbDelete.setEnabled(False)
        self.btnDbDelete.setObjectName("btnDbDelete")
        self.horizontalLayout.addWidget(self.btnDbDelete)
        spacerItem4 = QtWidgets.QSpacerItem(37, 17,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem4)
        self.btnDbRefresh = QtWidgets.QPushButton(self.widgetDatabases)
        self.btnDbRefresh.setObjectName("btnDbRefresh")
        self.horizontalLayout.addWidget(self.btnDbRefresh)
        self.verticalLayout_3.addLayout(self.horizontalLayout)
        self.gridLayout_5.addWidget(self.widgetDatabases, 2, 0, 1, 1)
        self.line_4 = QtWidgets.QFrame(self.accountTab)
        self.line_4.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_4.setObjectName("line_4")
        self.gridLayout_5.addWidget(self.line_4, 3, 0, 1, 1)
        self.tabWidget.addTab(self.accountTab, "")
        self.aboutTab = QtWidgets.QWidget()
        self.aboutTab.setObjectName("aboutTab")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.aboutTab)
        self.verticalLayout.setObjectName("verticalLayout")
        self.logo = QtWidgets.QLabel(self.aboutTab)
        self.logo.setAutoFillBackground(False)
        self.logo.setPixmap(QtGui.QPixmap(":/plugins/qgiscloud/logo.png"))
        self.logo.setScaledContents(False)
        self.logo.setAlignment(QtCore.Qt.AlignCenter)
        self.logo.setObjectName("logo")
        self.verticalLayout.addWidget(self.logo)
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.label_6 = QtWidgets.QLabel(self.aboutTab)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_6.sizePolicy().hasHeightForWidth())
        self.label_6.setSizePolicy(sizePolicy)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_8.addWidget(self.label_6)
        self.lblVersionPlugin = QtWidgets.QLabel(self.aboutTab)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.lblVersionPlugin.sizePolicy().hasHeightForWidth())
        self.lblVersionPlugin.setSizePolicy(sizePolicy)
        self.lblVersionPlugin.setText("")
        self.lblVersionPlugin.setObjectName("lblVersionPlugin")
        self.horizontalLayout_8.addWidget(self.lblVersionPlugin)
        self.verticalLayout.addLayout(self.horizontalLayout_8)
        self.aboutText = QtWidgets.QTextEdit(self.aboutTab)
        self.aboutText.setObjectName("aboutText")
        self.verticalLayout.addWidget(self.aboutText)
        self.tabWidget.addTab(self.aboutTab, "")
        self.gridLayout_3.addWidget(self.tabWidget, 1, 0, 1, 1)
        QgisCloudPlugin.setWidget(self.dockWidgetContents)
        self.label_2.setBuddy(self.editServer)

        self.retranslateUi(QgisCloudPlugin)
        self.tabWidget.setCurrentIndex(2)
        QtCore.QMetaObject.connectSlotsByName(QgisCloudPlugin)
예제 #28
0
 def clearImage(self):
     self.image.fill(QtGui.qRgb(255, 255, 255))
     self.modified = True
     self.update()
예제 #29
0
    def __init__(self, parent=None, iface=None, dock_widget=None):
        """Constructor for the dialog.

        Show the grid converter dialog.

        :param parent: parent - widget to use as parent.
        :type parent: QWidget

        :param iface: QGIS QgisAppInterface instance.
        :type iface: QgisAppInterface

        :param dock_widget: Dock widget instance.
        :type dock_widget: Dock
        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.iface = iface
        self.dock_widget = dock_widget
        self.setupUi(self)
        self.setWindowTitle(
            tr('InaSAFE %s Shakemap Converter' % get_version()))
        icon = resources_path('img', 'icons', 'show-converter-tool.svg')
        self.setWindowIcon(QtGui.QIcon(icon))
        self.warning_text = set()
        self.on_input_path_textChanged()
        self.on_output_path_textChanged()
        self.update_warning()
        self.output_layer = None

        # Event register
        # noinspection PyUnresolvedReferences
        self.use_output_default.toggled.connect(
            self.get_output_from_input)
        # noinspection PyUnresolvedReferences
        self.input_path.textChanged.connect(self.on_input_path_textChanged)
        # noinspection PyUnresolvedReferences
        self.output_path.textChanged.connect(self.on_output_path_textChanged)
        self.load_result.clicked.connect(self.load_result_toggled)

        # Set up things for context help
        self.help_button = self.button_box.button(QDialogButtonBox.Help)
        # Allow toggling the help button
        self.help_button.setCheckable(True)
        self.help_button.toggled.connect(self.help_toggled)
        self.main_stacked_widget.setCurrentIndex(1)
        self.check_box_custom_shakemap_id.toggled.connect(
            self.line_edit_shakemap_id.setEnabled)

        # Set value for EQ source type combo box
        self.combo_box_source_type.addItem(tr('N/A'), '')
        for source_type in extra_keyword_earthquake_source['options']:
            self.combo_box_source_type.addItem(
                source_type['name'], source_type['key'])
        self.combo_box_source_type.setCurrentIndex(0)

        self.update_warning()

        if not setting('developer_mode', expected_type=bool):
            self.smoothing_group_box.hide()

        self.use_ascii_mode.setToolTip(tr(
            'This algorithm will convert the grid xml to a ascii raster file. '
            'If the cell width and height is different, it will use the width '
            '(length cell in x axis).'))

        if not HAS_SCIPY:
            if self.scipy_smoothing.isChecked:
                self.none_smoothing.setChecked(True)
            self.scipy_smoothing.setToolTip(tr(
                'You can not use select this option since you do not have '
                'scipy installed in you system.'))
            self.scipy_smoothing.setEnabled(False)
        else:
            self.scipy_smoothing.setEnabled(True)
            self.scipy_smoothing.setToolTip('')
예제 #30
0
    def __init__(self, parent, combos, coord=None):

        if not coord:
            coord = ["", None, None, ""]
        super(LegalRestrictionsDialog, self).__init__(parent)
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)
        self.setupUi(self)
        self.setModal(True)
        self.restrict_dic = combos[0]
        self.combo_accessrestrictions.setModel(
            CustomComboBoxModel(
                self, [None] +
                sorted(list(combos[0].values()), key=lambda x: x.term_pt)))
        self.combo_userestrictions.setModel(
            CustomComboBoxModel(
                self, [None] +
                sorted(list(combos[0].values()), key=lambda x: x.term_pt)))
        self.btn_cancel.clicked.connect(lambda: self.done(QDialog.Rejected))
        self.btn_add.clicked.connect(lambda: self.done(QDialog.Accepted))
        self.line_uselimitations.textChanged.connect(self.checkInput)
        self.combo_accessrestrictions.currentIndexChanged.connect(
            self.checkInput)
        self.combo_userestrictions.currentIndexChanged.connect(self.checkInput)
        self.line_otherrestrictions.textEdited.connect(self.checkInput)

        self.line_uselimitations.setText(coord[0])
        if coord[1] is not None:
            buf = combos[0].get(coord[1].term, None)
            if buf is not None:
                self.combo_accessrestrictions.setCurrentIndex(
                    self.combo_accessrestrictions.findText(buf.term_pt))

        if coord[2] is not None:
            buf = combos[0].get(coord[2].term, None)
            if buf is not None:
                self.combo_userestrictions.setCurrentIndex(
                    self.combo_userestrictions.findText(buf.term_pt))

        self.line_otherrestrictions.setText(coord[3])
        self.checkInput()

        tla.setupMandatoryField(None, self.line_uselimitations,
                                self.label_line_uselimitations,
                                u"Elemento Obrigatório.")
        tla.setupMandatoryField(None, self.combo_accessrestrictions,
                                self.label_combo_accessrestrictions,
                                u"Elemento Obrigatório.")
        tla.setupMandatoryField(None, self.combo_userestrictions,
                                self.label_combo_userestrictions,
                                u"Elemento Obrigatório.")
        self.superParent = None
        temp = self.parent()
        while self.superParent is None:
            if issubclass(type(temp), restrictionsPanel.Ui_restrictions):
                self.superParent = temp
            else:
                temp = temp.parent()
        for info in self.findChildren(qgui.QPushButton,
                                      qcore.QRegExp('info_*')):
            info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg'))
            info.setText('')
            info.pressed.connect(self.printHelp)