def run(self):
        """Run method that starts all the real work"""
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start:
            self.first_start = False
            self.dlg = ProevenVerzamelingDialog()
            self.reset_ui()
            # Initialize QGIS filewidget to select a directory
            self.dlg.fileWidget.setStorageMode(1)
            # Signalling the Open button. Here the actual logic behind the plugin starts
            self.dlg.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(
                self.read_form)
            # Signalling the reset button.
            self.dlg.buttonBox.button(
                QDialogButtonBox.RestoreDefaults).clicked.connect(
                    self.reset_ui)
            rx1 = QRegExp(r"^\[\d{1,2}(\.\d{1})?(?:,\d{1,2}(\.\d{1})?)+\]$")
            vg_validator = QRegExpValidator(rx1)
            self.dlg.le_vg_sdp.setValidator(vg_validator)
            self.dlg.le_vg_trx.setValidator(vg_validator)

            rx2 = QRegExp(r"^[\w\-. ]+$")
            filename_validator = QRegExpValidator(rx2)
            self.dlg.le_outputName.setValidator(filename_validator)

        # show the dialog
        self.dlg.show()
Exemplo n.º 2
0
    def __init__(self, parent=None):
        QSyntaxHighlighter.__init__(self, parent)
        self.parent = parent
        sqlKeyword = QTextCharFormat()
        sqlOperator = QTextCharFormat()

        self.highlightingRules = []

        # Keywords
        sqlKeyword.setFontWeight(QFont.Bold)
        sqlKeyword.setForeground(Qt.blue)

        sqlKeywords = ["AND", "OR", "LIKE"]
        for word in sqlKeywords:
            regExp = QRegExp("\\b" + word + "\\b", Qt.CaseInsensitive)
            rule = HighlightingRule(regExp, sqlKeyword)
            self.highlightingRules.append(rule)

        # Comparison Operators
        sqlOperator.setForeground(Qt.magenta)
        sqlOperators = ["<", ">", "="]
        for operator in sqlOperators:
            regExp = QRegExp("\\W" + operator + "\\W", Qt.CaseInsensitive)
            rule = HighlightingRule(regExp, sqlOperator)
            self.highlightingRules.append(rule)
def set_regexp_date_validator(widget, button=None, regex_type=1):
    """ Set QRegExpression in order to validate QLineEdit(widget) field type date.
    Also allow to enable or disable a QPushButton(button), like typical accept button
    @Type=1 (yyy-mm-dd), @Type=2 (dd-mm-yyyy)
    """
    placeholder = "yyyy-mm-dd"
    if regex_type == 1:
        widget.setPlaceholderText("yyyy-mm-dd")
        placeholder = "yyyy-mm-dd"
        reg_exp = QRegExp(
            "(((\d{4})([-])(0[13578]|10|12)([-])(0[1-9]|[12][0-9]|3[01]))|"
            "((\d{4})([-])(0[469]|11)([-])([0][1-9]|[12][0-9]|30))|"
            "((\d{4})([-])(02)([-])(0[1-9]|1[0-9]|2[0-8]))|"
            "(([02468][048]00)([-])(02)([-])(29))|"
            "(([13579][26]00)([-])(02)([-])(29))|"
            "(([0-9][0-9][0][48])([-])(02)([-])(29))|"
            "(([0-9][0-9][2468][048])([-])(02)([-])(29))|"
            "(([0-9][0-9][13579][26])([-])(02)([-])(29)))")
    elif regex_type == 2:
        widget.setPlaceholderText("dd-mm-yyyy")
        placeholder = "dd-mm-yyyy"
        reg_exp = QRegExp(
            "(((0[1-9]|[12][0-9]|3[01])([-])(0[13578]|10|12)([-])(\d{4}))|"
            "(([0][1-9]|[12][0-9]|30)([-])(0[469]|11)([-])(\d{4}))|"
            "((0[1-9]|1[0-9]|2[0-8])([-])(02)([-])(\d{4}))|"
            "((29)(-)(02)([-])([02468][048]00))|"
            "((29)([-])(02)([-])([13579][26]00))|"
            "((29)([-])(02)([-])([0-9][0-9][0][48]))|"
            "((29)([-])(02)([-])([0-9][0-9][2468][048]))|"
            "((29)([-])(02)([-])([0-9][0-9][13579][26])))")

    widget.setValidator(QRegExpValidator(reg_exp))
    widget.textChanged.connect(
        partial(eval_regex, widget, reg_exp, button, placeholder))
Exemplo n.º 4
0
 def prepareLayout(self):
     """Przygotowanie layoutu SMTP"""
     self.port_lineEdit.setValidator(QRegExpValidator(QRegExp("[0-9]*")))
     self.host_lineEdit.setValidator(QRegExpValidator(QRegExp(r"\S*")))
     self.receiver_lineEdit.setValidator(
         QRegExpValidator(QRegExp(r"[0-9a-zA-Z.\-\_\@\+]*")))
     self.user_lineEdit.setValidator(
         QRegExpValidator(QRegExp(r"[0-9a-zA-Z.\-\_\@\+]*")))
     self.readSettings("smtp")  # wczytaj zapisane wartości
     self.cancel_btn.clicked.connect(self.close)
     self.send_btn.clicked.connect(self.send_btn_clicked)
     self.save_btn.clicked.connect(lambda: self.saveSettings("smtp"))
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        self.dlg = ConstIdentificacionDialog(parent=iface.mainWindow())
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'ConstIdentificacion_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Constancia Identificacion')
        self.abrePredio5 = False
        self.directorioAGuardar5 = None
        self.cve_catastral5 = None

        self.canvas = iface.mapCanvas()

        # eventos
        self.dlg.btnBrowse_4.clicked.connect(self.selectDirectory4)
        self.dlg.btnGenerar_4.clicked.connect(self.generarDoc4)
        self.dlg.btnSeleccionar_4.clicked.connect(self.activarSeleccion4)
        self.dlg.exit_signal.connect(self.closeEvent)

        self.dlg.fldCveCat_4.textChanged.connect(self.lineEditToUpper4)

        #validaciones
        rx = QRegExp("[a-zA-Z0-9]{31}")
        val = QRegExpValidator(rx)
        self.dlg.fldCveCat_4.setValidator(val)

        rx = QRegExp("[a-zA-ZÀ-ÿ ]{255}")
        val = QRegExpValidator(rx)
        self.dlg.fldNomSolic.setValidator(val)

        self.onlyInt = QIntValidator()
        self.dlg.fldNumSolucitud.setValidator(self.onlyInt)

        self.dlg.dateEdit_2.setDate(QDate.currentDate())
Exemplo n.º 6
0
    def prepareLayout(self):
        """Przygotowanie layoutu metadanych"""
        for listWidget in utils.getWidgetsByType(self, QListWidget):
            self.prepareListWidgets(listWidget)

        # pola z ustawień
        initializeMetadataForm(self)
        # pola edytowalne
        metadataElementDictToForm(
            metadataElementDict=dictionaries.metadataListWidgetsDefaultItems,
            targetForm=self)

        p = QPixmap(':/plugins/wtyczka_app/img/info1.png')

        # Ograniczenia Pól QLineEdit
        # URI:
        for objectName in ["e4_lineEdit"]:
            input = utils.getWidgetByName(self, QLineEdit, objectName)
            input.setValidator(QRegExpValidator(QRegExp(r"\S*")))

        # mail:
        for objectName in ["e22_mail_lineEdit", "e29_mail_lineEdit"]:
            input = utils.getWidgetByName(self, QLineEdit, objectName)
            input.setValidator(
                QRegExpValidator(QRegExp(r"[0-9a-zA-Z.\-\_\@\+]*")))

        # unikalny identyfikator danych przestrzennych:
        input = utils.getWidgetByName(self, QLineEdit, "e5_lineEdit")
        input.setValidator(QRegExpValidator(QRegExp(r"[0-9A-Z.\-/]*")))

        # prostokat ograniczajacy
        input = utils.getWidgetByName(self, QLineEdit, "e11_lineEdit")
        input.setValidator(QRegExpValidator(QRegExp("[0-9.,]*")))

        # rozdzielczość przestrzenna
        input = utils.getWidgetByName(self, QLineEdit, "e16_lineEdit")
        input.setValidator(QRegExpValidator(QRegExp("[0-9]*")))

        # czyszczenie QgsDateTimeEdit
        for dateTimeEdit in utils.getWidgetsByType(self, QDateTimeEdit):
            if dateTimeEdit.objectName() != 'e30_dateTimeEdit':
                dateTimeEdit.clear()

        # nadanie grafiki tooltipa
        for label in utils.getWidgetsByType(self, QLabel):
            if label.objectName().endswith("_tooltip"):
                label.setMaximumWidth(16)
                label.setPixmap(p.scaled(16, 16, Qt.KeepAspectRatio))

                label.setToolTip(
                    "<FONT COLOR=black>%s</FONT>" % label.toolTip()
                )  # dodanie tooltip z documentation 'rich text' dla zawijania
Exemplo n.º 7
0
    def __init__(self, parent=None):
        super().__init__(parent)

        keyword_format = QTextCharFormat()
        keyword_format.setForeground(Qt.darkMagenta)

        keyword_patterns = [
            "\\b?xml\\b", "/>", ">", "<", ";", "\[", "\]", "\(", "\)"
        ]

        self.highlightingRules = [(QRegExp(pattern), keyword_format)
                                  for pattern in keyword_patterns]

        element_format = QTextCharFormat()
        element_format.setForeground(QColor("#117700"))
        self.highlightingRules.append(
            (QRegExp("\\b[A-Za-z_\-]+(?=[\s\/>:;])"), element_format))

        nominatim_area_format = QTextCharFormat()
        nominatim_area_format.setFontItalic(True)
        nominatim_area_format.setFontWeight(QFont.Bold)
        nominatim_area_format.setForeground(QColor("#FF7C00"))
        self.highlightingRules.append(
            (QRegExp("\{\{[A-Za-z0-9:, ]*\}\}"), nominatim_area_format))

        attribute_format = QTextCharFormat()
        attribute_format.setFontItalic(True)
        attribute_format.setForeground(QColor("#2020D2"))
        self.highlightingRules.append(
            (QRegExp("\\b[A-Za-z0-9_-]+(?=\\=|\\[|\\(|$|\\.)"),
             attribute_format))

        value_format = QTextCharFormat()
        value_format.setForeground(Qt.red)
        self.highlightingRules.append(
            (QRegExp("(\"[A-Za-z0-9:, _.]*\"|\:([0-9]+)(?=\,|\]))"),
             value_format))

        area_format = QTextCharFormat()
        area_format.setForeground(QColor("#11CC00"))
        area_pattern = [
            "\.([A-Za-z0-9_]{2,})(?=\\)|\\;)", "\(([0-9]{2,})\)",
            "[0-9]+[.]+[0-9]+"
        ]
        for pattern in area_pattern:
            self.highlightingRules.append((QRegExp(pattern), area_format))

        single_line_comment_format = QTextCharFormat()
        single_line_comment_format.setForeground(Qt.gray)
        self.highlightingRules.append(
            (QRegExp("(<!--[^\n]*-->|//[^\n]*)"), single_line_comment_format))

        # Multi lines comment
        self.oql_start_comment = QRegExp("\/\*")
        self.oql_end_comment = QRegExp('\*\/')
Exemplo n.º 8
0
    def __init__(self, document):
        QSyntaxHighlighter.__init__(self, document.document())
        #msgBox=QMessageBox()
        #msgBox.setText(document.toPlainText())
        #msgBox.exec()
        # Multi-line strings (expression, flag, style)
        # FIXME: The triple-quotes in these two lines will mess up the
        # syntax highlighting from this point onward
        self.tri_single = (QRegExp("'''"), 1, STYLES['string2'])
        self.tri_double = (QRegExp('"""'), 2, STYLES['string2'])
  
        rules = []
  
  
          # All other rules
        rules += [
            # 'self'
            (r'\bself\b', 0, STYLES['self']),
  
            # Double-quoted string, possibly containing escape sequences
            (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
            # Single-quoted string, possibly containing escape sequences
            (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
  
            # 'def' followed by an identifier
            (r'([?]\w+)', 1, STYLES['defclass']),
            (r'([<][h][t][t][p][:][/][/]\w+[>])', 0, STYLES['uri']),
			# 'class' followed by an identifier
            (r'(\w+[:]\w+)', 1, STYLES['uri']),
			
  
            # From '#' until a newline
            (r'#[^\n]*', 0, STYLES['comment']),
  
            # Numeric literals
            (r'\b[+-]?[0-9]+[lL]?\b', 0, STYLES['numbers']),
            (r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b', 0, STYLES['numbers']),
            (r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b', 0, STYLES['numbers']),
        ]
		        # Keyword, operator, and brace rules
        rules += [(r'\b%s\b' % w, 0, STYLES['keyword'])
            for w in SPARQLHighlighter.keywords]
        rules += [(r'%s' % o, 0, STYLES['operator'])
            for o in SPARQLHighlighter.operators]
        rules += [(r'%s' % b, 0, STYLES['brace'])
            for b in SPARQLHighlighter.braces]
  
        # Build a QRegExp for each pattern
        self.rules = [(QRegExp(pat), index, fmt)
            for (pat, index, fmt) in rules]
Exemplo n.º 9
0
 def __init__(self, parent=None):
     """Constructor."""
     super(UstawieniaDialog, self).__init__(parent)
     self.setupUi(self)
     self.setWindowTitle(title_settings)
     self.setWindowIcon(QtGui.QIcon(icon_settings))
     self.setWindowFlags(Qt.WindowMinimizeButtonHint
                         | Qt.WindowSystemMenuHint
                         | Qt.WindowMinMaxButtonsHint
                         | Qt.WindowCloseButtonHint)
     self.exit_btn.clicked.connect(self.reject)
     self.contactMail_lineEdit.setValidator(
         QRegExpValidator(QRegExp(r"[0-9a-zA-Z.\-\_\@\+]*")))
     self.adminMail_lineEdit.setValidator(
         QRegExpValidator(QRegExp(r"[0-9a-zA-Z.\-\_\@\+]*")))
 def __init__(self, triplestoreconf, prefixes, prefixstore, comboBox):
     super(QDialog, self).__init__()
     self.setupUi(self)
     self.triplestoreconf = triplestoreconf
     self.prefixstore = prefixstore
     self.comboBox = comboBox
     self.prefixes = prefixes
     for item in triplestoreconf:
         self.tripleStoreChooser.addItem(item["name"])
     self.tripleStoreChooser.currentIndexChanged.connect(
         self.loadTripleStoreConfig)
     #self.addTripleStoreButton.clicked.connect(self.addNewSPARQLEndpoint)
     urlregex = QRegExp(
         "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
     )
     urlvalidator = QRegExpValidator(urlregex, self)
     self.tripleStoreEdit.setValidator(urlvalidator)
     self.tripleStoreEdit.textChanged.connect(self.check_state1)
     self.tripleStoreEdit.textChanged.emit(self.tripleStoreEdit.text())
     self.epsgEdit.setValidator(QIntValidator(1, 100000))
     prefixregex = QRegExp("[a-z]+")
     prefixvalidator = QRegExpValidator(prefixregex, self)
     self.tripleStorePrefixNameEdit.setValidator(prefixvalidator)
     self.addPrefixButton.clicked.connect(self.addPrefixToList)
     self.removePrefixButton.clicked.connect(self.removePrefixFromList)
     self.testConnectButton.clicked.connect(self.testTripleStoreConnection)
     self.deleteTripleStore.clicked.connect(self.deleteTripleStoreFunc)
     self.resetConfiguration.clicked.connect(self.restoreFactory)
     self.newTripleStore.clicked.connect(self.createNewTripleStore)
     #self.exampleQuery.textChanged.connect(self.validateSPARQL)
     self.sparqlhighlighter = SPARQLHighlighter(self.exampleQuery)
     self.tripleStorePrefixEdit.setValidator(urlvalidator)
     self.tripleStorePrefixEdit.textChanged.connect(self.check_state2)
     self.tripleStorePrefixEdit.textChanged.emit(
         self.tripleStorePrefixEdit.text())
     self.tripleStoreApplyButton.clicked.connect(
         self.applyCustomSPARQLEndPoint)
     self.tripleStoreCloseButton.clicked.connect(
         self.closeTripleStoreDialog)
     self.detectConfiguration.clicked.connect(
         self.detectTripleStoreConfiguration)
     s = QSettings()  #getting proxy from qgis options settings
     self.proxyEnabled = s.value("proxy/proxyEnabled")
     self.proxyType = s.value("proxy/proxyType")
     self.proxyHost = s.value("proxy/proxyHost")
     self.proxyPort = s.value("proxy/proxyPort")
     self.proxyUser = s.value("proxy/proxyUser")
     self.proxyPassword = s.value("proxy/proxyPassword")
Exemplo n.º 11
0
    def __init__(self):
        """Constructor for the dialog.

        """

        QDialog.__init__(self)

        self.setupUi(self)

        self.btnsave = self.buttonBox.button(QDialogButtonBox.Save)

        self.saveCtrl()

        re = QRegExp('[0-9.]+')
        val = QRegExpValidator(re)
        self.lineEdit_longitude.setValidator(val)
        self.lineEdit_2_latitude.setValidator(val)

        self.toolButton.setToolTip('Degree - decimal conversion')
        self.toolButton.clicked.connect(self.trafo)

        self.lineEdit_3.textChanged.connect(self.saveCtrl)
        self.lineEdit_5.textChanged.connect(self.saveCtrl)
        self.comboBox.currentIndexChanged.connect(self.saveCtrl)

        self.funcs = VetEpiGISFuncs()
Exemplo n.º 12
0
    def _configure_table_editor_properties(self, base_table_editor):
        qgis_version = QGis.QGIS_VERSION_INT
        #Get scroll area first
        scroll_area = base_table_editor.findChild(QScrollArea, "scrollArea")

        if not scroll_area is None:

            contents_widget = scroll_area.widget()
            object_names = ['^mRefreshPushButton$'
                            ]  ##, '^mLayerLabel$', '^mLayerComboBox$', ]

            for object_name in object_names:
                name_regex = QRegExp(object_name)
                for widget in contents_widget.findChildren(
                        QWidget, name_regex):
                    widget.setVisible(False)

                # main_properties_groupbox = contents_widget.findChild(QGroupBox, "groupBox")
                # #Version 2.4
                # if qgis_version >= 20400 and qgis_version <= 20600:
                #     self._hide_filter_controls(main_properties_groupbox)

            # if qgis_version >= 20600:
            #     feature_filter_groupbox = contents_widget.findChild(QGroupBox, "groupBox_5")
            # if not feature_filter_groupbox is None:
            #     self._hide_filter_controls(feature_filter_groupbox)
            appearance_groupbox = contents_widget.findChild(
                QGroupBox, "groupBox_6")
            appearance_groupbox.setVisible(True)
    def clicked_event(self):

        # Create the dialog
        self.dlg_manager = EpaManager()
        load_settings(self.dlg_manager)

        # Manage widgets
        reg_exp = QRegExp("^[A-Za-z0-9_]{1,16}$")
        self.dlg_manager.txt_result_id.setValidator(QRegExpValidator(reg_exp))

        # Fill combo box and table view
        self.fill_combo_result_id()
        self.dlg_manager.tbl_rpt_cat_result.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        fill_table(self.dlg_manager.tbl_rpt_cat_result, 'v_ui_rpt_cat_result')
        set_table_columns(self.dlg_manager,
                          self.dlg_manager.tbl_rpt_cat_result,
                          'v_ui_rpt_cat_result')

        # Set signals
        self.dlg_manager.btn_delete.clicked.connect(
            partial(multi_rows_delete, self.dlg_manager.tbl_rpt_cat_result,
                    'rpt_cat_result', 'result_id'))
        self.dlg_manager.btn_close.clicked.connect(
            partial(close_dialog, self.dlg_manager))
        self.dlg_manager.rejected.connect(
            partial(close_dialog, self.dlg_manager))
        self.dlg_manager.txt_result_id.editTextChanged.connect(
            self.filter_by_result_id)

        # Open form
        open_dialog(self.dlg_manager, dlg_name='go2epa_manager')
Exemplo n.º 14
0
    def _accept(self):
        filename = unicode(self.dlg.uXmlFile.text())
        homedir = os.path.dirname(filename)
        settings = QSettings()
        settings.setValue(self.browsePathSetting, homedir)

        if not filename:
            QMessageBox.information(
                self.dlg, "M150Xml error",
                "You must specify a M150Xml file to import")
            return
        if not os.path.exists(filename):
            QMessageBox.information(self.dlg, "M150Xml error",
                                    "Cannot open " + filename)
            return

        #try:
        if QRegExp('\.xml$', Qt.CaseInsensitive).indexIn(filename) > -1:
            self.dlg.uXmlFile.setText(filename)

            data = M150XmlImp(filename)
            if self.dlg.uImportParcels.isChecked():
                self._createHaltungsLayer(data)
            if self.dlg.uImportMarks.isChecked():
                self._createSchachtLayer(data)
            if self.dlg.uImportObs.isChecked():
                self._createInspektionsLayer(data)
                self._createStationsLayer(data)
                self._createInspektionsLayerSchacht(data)
                self._createStationsLayerSchacht(data)
Exemplo n.º 15
0
def pg_tables(schema="public", exclude_lookups=False):
    """
    Returns a list of all the tables in the given schema minus the default PostGIS tables.
    Views are also excluded. See separate function for retrieving views.
    :rtype: list
    """
    t = text(
        "SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype "
        "ORDER BY table_name ASC")
    result = _execute(t, tschema=schema, tbtype="BASE TABLE")

    pgTables = []

    for r in result:
        tableName = r["table_name"]

        # Remove default PostGIS tables
        tableIndex = getIndex(_postGISTables, tableName)
        if tableIndex != -1:
            continue
        if exclude_lookups:
            # Validate if table is a lookup table and if it is, then omit
            rx = QRegExp("check_*")
            rx.setPatternSyntax(QRegExp.Wildcard)

            if not rx.exactMatch(tableName):
                pgTables.append(tableName)

        else:
            pgTables.append(tableName)

    return pgTables
    def __init__(self, parent, coord=None):

        if not coord:
            coord = [0, 0, 0, 0, True]
        super(GeoLocalizationDialog, self).__init__(parent)
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)
        self.setupUi(self)

        self.check_haveresources.setChecked(coord[4])
        self.setModal(True)
        self.btn_cancel.clicked.connect(lambda: self.done(QDialog.Rejected))
        self.btn_add.clicked.connect(lambda: self.done(QDialog.Accepted))
        self.spin_west_limit.setValue(float(str(coord[0]).replace(",", ".")))
        self.spin_east_limit.setValue(float(str(coord[1]).replace(",", ".")))
        self.spin_north_limit.setValue(float(str(coord[2]).replace(",", ".")))
        self.spin_south_south.setValue(float(str(coord[3]).replace(",", ".")))
        self.spin_west_limit.setDecimals(5)
        self.spin_east_limit.setDecimals(5)
        self.spin_north_limit.setDecimals(5)
        self.spin_south_south.setDecimals(5)
        self.superParent = None
        temp = self.parent()
        while self.superParent is None:
            if issubclass(type(temp),
                          geographicinformationPanel.Ui_geographicinfo):
                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)
Exemplo n.º 17
0
    def __init__(self, parent=None):
        super(LCDefineDegradationWidget, self).__init__(parent)

        self.setupUi(self)

        self.classes = [self.tr("Tree-covered"),
                        self.tr("Grassland"),
                        self.tr("Cropland"),
                        self.tr("Wetland"),
                        self.tr("Artificial"),
                        self.tr("Bare land"),
                        self.tr("Water body")]
        self.deg_def_matrix.setRowCount(len(self.classes))
        self.deg_def_matrix.setColumnCount(len(self.classes))
        self.deg_def_matrix.setHorizontalHeaderLabels(self.classes)
        self.deg_def_matrix.setVerticalHeaderLabels(self.classes)

        self.trans_matrix_default = [0, -1, -1, -1, -1, -1, 0, # Tree-covered
                                     1, 0, 1, -1, -1, -1, 0, # grassland
                                     1, -1, 0, -1, -1, -1, 0, # cropland
                                     -1, -1, -1, 0, -1, -1, 0, # wetland
                                     1, 1, 1, 1, 0, 1, 0, # artificial
                                     1, 1, 1, 1, -1, 0, 0, # Other land
                                     0, 0, 0, 0, 0, 0, 0] # water body
        for row in range(0, self.deg_def_matrix.rowCount()):
            for col in range(0, self.deg_def_matrix.columnCount()):
                line_edit = TransMatrixEdit()
                line_edit.setValidator(QRegExpValidator(QRegExp("[-0+]")))
                line_edit.setAlignment(Qt.AlignHCenter)
                self.deg_def_matrix.setCellWidget(row, col, line_edit)
        self.trans_matrix_set()

        # Setup the vertical label for the rows of the table
        label_lc_baseline_year = VerticalLabel(self)
        label_lc_baseline_year.setText(QtWidgets.QApplication.translate("DlgCalculateLC", "Land cover in initial year ", None))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_lc_target_year.sizePolicy().hasHeightForWidth())
        label_lc_baseline_year.setSizePolicy(sizePolicy)
        font = QFont()
        font.setBold(True)
        font.setWeight(75)
        label_lc_baseline_year.setFont(font)
        self.lc_trans_table_layout.addWidget(label_lc_baseline_year, 1, 0, 1, 1, Qt.AlignCenter)

        self.deg_def_matrix.setStyleSheet('QTableWidget {border: 0px;}')
        self.deg_def_matrix.horizontalHeader().setStyleSheet('QHeaderView::section {background-color: white;border: 0px;}')
        self.deg_def_matrix.verticalHeader().setStyleSheet('QHeaderView::section {background-color: white;border: 0px;}')

        self.deg_def_matrix.horizontalHeader().setResizeMode(QtWidgets.QHeaderView.Stretch)
        self.deg_def_matrix.verticalHeader().setResizeMode(QtWidgets.QHeaderView.Stretch)

        self.btn_transmatrix_reset.clicked.connect(self.trans_matrix_set)
        self.btn_transmatrix_loadfile.clicked.connect(self.trans_matrix_loadfile)
        self.btn_transmatrix_savefile.clicked.connect(self.trans_matrix_savefile)

        self.legend_deg.setStyleSheet('QLineEdit {background: #AB2727;} QLineEdit:hover {border: 1px solid gray; background: #AB2727;}')
        self.legend_imp.setStyleSheet('QLineEdit {background: #45A146;} QLineEdit:hover {border: 1px solid gray; background: #45A146;}')
        self.legend_stable.setStyleSheet('QLineEdit {background: #FFFFE0;} QLineEdit:hover {border: 1px solid gray; background: #FFFFE0;}')
Exemplo n.º 18
0
 def create_fb(self):
     """ Create a new empty fieldbook from template and add to layer list. Layer/file name changed to start with
     'fb\\_' if neccessary.
     """
     ofname, __ = QFileDialog.getSaveFileName(
         self.iface.mainWindow(),
         tr('New fieldbook'),
         filter=tr('Fieldbook file (*.sqlite)'))
     if not ofname:
         return
     if QRegExp('fb_').indexIn(QFileInfo(ofname).baseName()):
         ofname = QDir.cleanPath(
             QFileInfo(ofname).absolutePath() + QDir().separator() + 'fb_' +
             QFileInfo(ofname).fileName())
     ofbase = QDir.cleanPath(
         QFileInfo(ofname).absolutePath() + QDir().separator() +
         QFileInfo(ofname).baseName())
     tempbase = QDir.cleanPath(self.plugin_dir + QDir().separator() +
                               'template' + QDir().separator() +
                               'fb_template')
     QFile(tempbase + '.sqlite').copy(ofbase + '.sqlite')
     fb = QgsVectorLayer(ofbase + '.sqlite',
                         QFileInfo(ofbase).baseName(), 'ogr')
     if fb.isValid():
         QgsProject.instance().addMapLayer(fb)
 def filterModel(self, col=None):
     if col != None:
         self.proxyModel.setFilterKeyColumn(col)
         expr = QRegExp("?*", Qt.CaseInsensitive, QRegExp.Wildcard)
         self.proxyModel.setFilterRegExp(expr)
     else:
         self.proxyModel.setFilterRegExp(None)
Exemplo n.º 20
0
    def highlightBlock(self, text: str):
        """Highlight of a comment block"""
        # for every pattern
        for pattern, char_format in self.highlightingRules:

            # Create a regular expression from the retrieved pattern
            expression = QRegExp(pattern)

            # Check what index that expression occurs at with the ENTIRE text
            index = expression.indexIn(text)

            # While the index is greater than 0
            while index >= 0:

                # Get the length of how long the expression is true,
                # set the format from the start to the length with
                # the text format
                length = expression.matchedLength()
                self.setFormat(index, length, char_format)

                # Set index to where the expression ends in the text
                index = expression.indexIn(text, index + length)

        # Do multi-line strings
        self.match_multiline(text, self.oql_start_comment,
                             self.oql_end_comment, 1, Qt.gray)
Exemplo n.º 21
0
 def create_coordlist(self):
     """ Create a new coordinate list from template and add to layer list. Layer/file name changed to start with
     'coord\\_' if neccessary.
     """
     ofname, __ = QFileDialog.getSaveFileName(
         self.iface.mainWindow(),
         tr('QGIS co-ordinate list'),
         filter=tr('SpatiaLite file (*.sqlite)'))
     if not ofname:
         return
     if QRegExp('coord_').indexIn(QFileInfo(ofname).baseName()):
         ofname = QDir.cleanPath(
             QFileInfo(ofname).absolutePath() + QDir().separator() +
             'coord_' + QFileInfo(ofname).fileName())
     ofbase = QDir.cleanPath(
         QFileInfo(ofname).absolutePath() + QDir().separator() +
         QFileInfo(ofname).baseName())
     tempbase = QDir.cleanPath(self.plugin_dir + QDir().separator() +
                               'template' + QDir().separator() +
                               'coord_template')
     QFile(tempbase + '.sqlite').copy(ofbase + '.sqlite')
     coord = QgsVectorLayer(ofbase + '.sqlite',
                            QFileInfo(ofbase).baseName(), 'ogr')
     if coord.isValid():
         QgsProject.instance().addMapLayer(coord)
    def __init__(self, db_connector, uri, type, parent=None):
        """
        Constructor
        :param db: database connection instance
        :param type: type of parameter to capture (database or schema)
        :param parent: parent of dialog
        """
        QDialog.__init__(self, parent)

        self.type = type
        self.db_connector = db_connector
        self.uri = uri
        self.parent = parent
        self.setupUi(self)

        if self.type == 'database':
            self.message_label.setText(
                QCoreApplication.translate("GetDBOrSchemaNameDialog",
                                           "Enter the name of the database:"))
            self.parameter_line_edit.setPlaceholderText(
                QCoreApplication.translate(
                    "GetDBOrSchemaNameDialog",
                    "[Name of the database to be created]"))
        else:
            self.message_label.setText(
                QCoreApplication.translate("GetDBOrSchemaNameDialog",
                                           "Enter the name of the schema:"))
            self.parameter_line_edit.setPlaceholderText(
                QCoreApplication.translate(
                    "GetDBOrSchemaNameDialog",
                    "[Name of the schema to be created]"))

        self.setWindowTitle(
            QCoreApplication.translate("GetDBOrSchemaNameDialog",
                                       "Create {type}").format(type=self.type))
        self.validators = Validators()

        # schema name mustn't have special characters
        regex = QRegExp("[a-zA-Z0-9_]+")
        validator = QRegExpValidator(regex)
        self.parameter_line_edit.setValidator(validator)
        self.parameter_line_edit.setMaxLength(63)
        self.parameter_line_edit.textChanged.connect(
            self.validators.validate_line_edits_lower_case)
        self.parameter_line_edit.textChanged.emit(
            self.parameter_line_edit.text())

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)

        self.buttonBox.accepted.disconnect()
        self.buttonBox.accepted.connect(self.accepted)
        self.buttonBox.clear()
        self.buttonBox.addButton(QDialogButtonBox.Cancel)
        self.buttonBox.addButton(
            QCoreApplication.translate("GetDBOrSchemaNameDialog",
                                       "Create {type}").format(type=self.type),
            QDialogButtonBox.AcceptRole)
Exemplo n.º 23
0
 def __init__(self,
              column,
              row,
              triplestoreconf,
              prefixes,
              interlinkOrEnrich,
              table,
              propOrClass=False,
              bothOptions=False,
              currentprefixes=None,
              addVocab=None):
     super(QDialog, self).__init__()
     self.setupUi(self)
     self.currentcol = column
     self.currentrow = row
     self.table = table
     self.prefixes = prefixes
     self.currentprefixes = currentprefixes
     self.bothOptions = bothOptions
     self.triplestoreconf = triplestoreconf
     self.interlinkOrEnrich = interlinkOrEnrich
     self.addVocab = addVocab
     if column != 4:
         self.findConcept.setChecked(True)
     if column == 4 or (not interlinkOrEnrich
                        and column != 4) or (not interlinkOrEnrich
                                             and propOrClass):
         self.findProperty.setChecked(True)
     if not bothOptions:
         self.findProperty.setEnabled(False)
         self.findConcept.setEnabled(False)
     self.tripleStoreEdit.setEnabled(False)
     for triplestore in self.triplestoreconf:
         if not "File" == triplestore["name"]:
             self.tripleStoreEdit.addItem(triplestore["name"])
     if addVocab != None:
         for cov in addVocab:
             self.tripleStoreEdit.addItem(addVocab[cov]["label"])
     self.searchButton.clicked.connect(self.getClassesFromLabel)
     urlregex = QRegExp(
         "http[s]?://(?:[a-zA-Z#]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
     )
     urlvalidator = QRegExpValidator(urlregex, self)
     self.costumproperty.setValidator(urlvalidator)
     self.costumproperty.textChanged.connect(self.check_state3)
     self.costumproperty.textChanged.emit(self.costumproperty.text())
     self.costumpropertyButton.clicked.connect(self.applyConceptToColumn2)
     self.applyButton.clicked.connect(self.applyConceptToColumn)
     s = QSettings()  #getting proxy from qgis options settings
     self.proxyEnabled = s.value("proxy/proxyEnabled")
     self.proxyType = s.value("proxy/proxyType")
     self.proxyHost = s.value("proxy/proxyHost")
     self.proxyPort = s.value("proxy/proxyPort")
     self.proxyUser = s.value("proxy/proxyUser")
     self.proxyPassword = s.value("proxy/proxyPassword")
     if self.proxyHost != None and self.ProxyPort != None:
         proxy = urllib.ProxyHandler({'http': proxyHost})
         opener = urllib.build_opener(proxy)
         urllib.install_opener(opener)
Exemplo n.º 24
0
 def __init__(self, settings):
     super(ConfigDialog, self).__init__(None)
     self.setupUi(self)
     SettingDialog.__init__(self, settings)
     self.settings = settings
     regex = QRegExp(MUNCODE_REGEX, Qt.CaseInsensitive)
     self.muncodeValidator = QRegExpValidator(regex)
     self.kommunefilter.setValidator(self.muncodeValidator)
Exemplo n.º 25
0
def supporting_doc_tables_regexp():
    """
    :return: Returns an instance of a Regex class for filtering supporting
    documents tables in the database.
    :rtype: QRegExp
    """
    doc_tables_filter = "|".join(SUPPORTING_DOC_TAGS)
    return QRegExp(doc_tables_filter)
Exemplo n.º 26
0
    def prepareLayout(self):
        """Przygotowanie layoutu CSW"""

        self.host_lineEdit.setValidator(QRegExpValidator(QRegExp(r"\S*")))
        self.readSettings("csw")  # wczytaj zapisane wartości
        self.cancel_btn.clicked.connect(self.close)
        self.send_btn.clicked.connect(self.send_btn_clicked)
        self.save_btn.clicked.connect(lambda: self.saveSettings("csw"))
Exemplo n.º 27
0
    def __init__(self, parent):
        super(InlineServiceOperation, self).__init__(parent)
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)
        self.setupUi(self)

        self.parent = parent
        self.superParent = parent.superParent

        self.combo_items_dcp = customCombo.dic_to_CustomComboBox_dic(
            self.superParent.codelist["DCPCodeList"])

        tla.setupListView(self.dcp, CustomComboBox, self, comboList=list(self.combo_items_dcp.values()), NoParent=True)
        tla.setupListView(self.connectionPoint, QgsFilterLineEdit, self, NoParent=True)
        tla.setupMandatoryField(None, self.operationName, self.label_operationName, u"Elemento Obrigatório.", )
        tla.setupMandatoryField(None, self.dcp, self.label_dcp, u"Obrigatório conter pelo menos uma entrada")
        tla.setupMandatoryField(None, self.connectionPoint, self.label_connectionPoint, u"Obrigatório conter pelo menos uma entrada")

        for btn in self.findChildren(QPushButton, QRegExp('btn_*')):
            if '_add_' in btn.objectName():
                btn.setIcon(QIcon(':/resourcesFolder/icons/plus_icon.svg'))
                btn.setText('')
            elif '_del_' in btn.objectName():
                btn.setIcon(QIcon(':/resourcesFolder/icons/delete_icon.svg'))
                btn.setText('')
        for info in self.findChildren(QPushButton, QRegExp('info_*')):
                     info.setIcon(QIcon(':/resourcesFolder/icons/help_icon.svg'))
                     info.setText('')
                     info.pressed.connect(self.printHelp)
        self.operationName.editingFinished.connect(self.update_title)
        self.update_title()
        self.btn_del_operation.setToolTip(u"Agagar Operação.")
        self.eater = tla.EatWheel()
        for x in self.findChildren(QComboBox):
            x.installEventFilter(self.eater)
            x.setFocusPolicy(Qt.StrongFocus)
        for x in self.findChildren(QDateTimeEdit):
            x.installEventFilter(self.eater)
            x.setFocusPolicy(Qt.StrongFocus)
        self.btn_del_operation.clicked.connect(self.deleteOperation)
        self.dcp.model().dataChanged.connect(self.update_title)
        self.connectionPoint.model().dataChanged.connect(self.update_title)
        self.combo_dcp.setCurrentIndex(self.combo_dcp.findText("WebServices"))
Exemplo n.º 28
0
    def __init__(self, parent=None, iface=None):
        """Constructor for import dialog.

        .. versionadded: 3.3

        :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)

        title = self.tr('PetaBencana Downloader')
        self.setWindowTitle(title)
        icon = resources_path('img', 'icons', 'add-petabencana-layer.svg')
        self.setWindowIcon(QtGui.QIcon(icon))

        self.iface = iface

        self.source = None

        self.radio_button_group = QButtonGroup()
        self.radio_button_group.addButton(self.radio_button_production)
        self.radio_button_group.addButton(self.radio_button_development)

        self.radio_button_group.setExclusive(True)
        self.radio_button_production.setChecked(True)
        self.populate_combo_box()

        developer_mode = setting('developer_mode', False, bool)
        if not developer_mode:
            self.radio_button_widget.hide()
            self.source_label.hide()
            self.output_group.adjustSize()

        # signals
        self.radio_button_production.clicked.connect(self.populate_combo_box)
        self.radio_button_development.clicked.connect(self.populate_combo_box)

        # 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)

        # 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)
        self.time_stamp = None
        self.restore_state()
Exemplo n.º 29
0
    def searchTextChanged(self, text):
        """Process a change in the search filter text."""
        # user adding characters and has exceeded 3 or more, or is removing characters
        if len(text) >= 3 or len(self.searchText) > len(text):
            regex = QRegExp(text, Qt.CaseInsensitive, QRegExp.RegExp)
            self.proxyModel.setFilterRegExp(regex)
            self.treeView.expandAll()

        # update last search text state
        self.searchText = text
Exemplo n.º 30
0
 def __init__(self, parent):
     super(ServiceOperationsWidget, self).__init__(parent)
     self.setupUi(self)
     self.op_box.setAlignment(Qt.AlignTop)
     self.superParent = self.parent()
     self.operationList = []
     self.btn_add_operations.clicked.connect(self.add_operation)
     self.check_mandatory_operations()
     for btn in self.findChildren(QPushButton, QRegExp('btn_*')):
         if '_add_' in btn.objectName():
             btn.setIcon(QIcon(':/resourcesFolder/icons/plus_icon.svg'))
             #  btn.setText('')
         elif '_del_' in btn.objectName():
             btn.setIcon(QIcon(':/resourcesFolder/icons/delete_icon.svg'))
             btn.setText('')
     for info in self.findChildren(QPushButton, QRegExp('info_*')):
         info.setIcon(QIcon(':/resourcesFolder/icons/help_icon.svg'))
         info.setText('')
         info.pressed.connect(self.printHelp)