コード例 #1
0
ファイル: xml_highlighter.py プロジェクト: Gustry/QuickOSM
    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)
コード例 #2
0
    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()
コード例 #3
0
ファイル: highlighter.py プロジェクト: ollawone/stdm
    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)
コード例 #4
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
コード例 #5
0
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))
コード例 #6
0
ファイル: highlighter.py プロジェクト: ollawone/stdm
    def highlightBlock(self, text):
        for rule in self.highlightingRules:
            expression = QRegExp(rule.pattern)
            index = expression.indexIn(text)

            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, rule.format)
                index = expression.indexIn(text, index + length)

        self.setCurrentBlockState(0)
コード例 #7
0
ファイル: featureform.py プロジェクト: skylning/Roam
 def findcontrol(self, name, all=False):
     regex = QRegExp("^{}$".format(QRegExp.escape(name)))
     regex.setCaseSensitivity(Qt.CaseInsensitive)
     try:
         if all:
             return self.findChildren(QWidget, regex)
         else:
             widget = self.findChildren(QWidget, regex)[0]
     except IndexError:
         widget = None
     return widget
コード例 #8
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"))
コード例 #9
0
    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())
コード例 #10
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
コード例 #11
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]
コード例 #12
0
ファイル: xml_highlighter.py プロジェクト: Gustry/QuickOSM
    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('\*\/')
コード例 #13
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.\-\_\@\+]*")))
コード例 #14
0
 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")
コード例 #15
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)
コード例 #16
0
    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')
コード例 #17
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)
コード例 #18
0
 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)
コード例 #19
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)
コード例 #20
0
    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)
コード例 #21
0
ファイル: lc_setup.py プロジェクト: giswt/trends.earth
    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;}')
コード例 #22
0
ファイル: m150xml.py プロジェクト: Amphibitus/m150xml
    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)
コード例 #23
0
ファイル: poi.py プロジェクト: IZSVenezie/VetEpiGIS-Tool
    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()
コード例 #24
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)
コード例 #25
0
    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)
コード例 #26
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)
コード例 #27
0
ファイル: supporting_documents.py プロジェクト: ollawone/stdm
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)
コード例 #28
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"))
コード例 #29
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"))
コード例 #30
0
ファイル: data_model.py プロジェクト: xzcvczx/QGIS
    def getObject(self, row):
        val = self.data(self.index(row, 0), Qt.UserRole)
        fld = val if val is not None else self._getNewObject()
        fld.name = self.data(self.index(row, 0)) or ""

        typestr = self.data(self.index(row, 1)) or ""
        regex = QRegExp("([^\\(]+)\\(([^\\)]+)\\)")
        startpos = regex.indexIn(typestr)
        if startpos >= 0:
            fld.dataType = regex.cap(1).strip()
            fld.modifier = regex.cap(2).strip()
        else:
            fld.modifier = None
            fld.dataType = typestr

        fld.notNull = self.data(self.index(row, 2), Qt.CheckStateRole) == Qt.Unchecked
        fld.primaryKey = self.data(self.index(row, 1), Qt.UserRole)
        return fld
コード例 #31
0
ファイル: data_model.py プロジェクト: Cracert/Quantum-GIS
    def getObject(self, row):
        val = self.data(self.index(row, 0), Qt.UserRole)
        fld = val if val is not None else self._getNewObject()
        fld.name = self.data(self.index(row, 0)) or ""

        typestr = self.data(self.index(row, 1)) or ""
        regex = QRegExp("([^\\(]+)\\(([^\\)]+)\\)")
        startpos = regex.indexIn(typestr)
        if startpos >= 0:
            fld.dataType = regex.cap(1).strip()
            fld.modifier = regex.cap(2).strip()
        else:
            fld.modifier = None
            fld.dataType = typestr

        fld.notNull = self.data(self.index(row, 2), Qt.CheckStateRole) == Qt.Unchecked
        fld.primaryKey = self.data(self.index(row, 1), Qt.UserRole)
        return fld
コード例 #32
0
ファイル: connector.py プロジェクト: NyakudyaA/QGIS
    def getSpatialRefInfo(self, srid):
        if not self.has_spatial:
            return

        try:
            c = self._execute(None, "SELECT srtext FROM spatial_ref_sys WHERE srid = '%d'" % srid)
        except DbError:
            return
        sr = self._fetchone(c)
        self._close_cursor(c)
        if sr is None:
            return

        srtext = sr[0]
        # try to extract just SR name (should be quoted in double quotes)
        regex = QRegExp('"([^"]+)"')
        if regex.indexIn(srtext) > -1:
            srtext = regex.cap(1)
        return srtext
コード例 #33
0
ファイル: plugin.py プロジェクト: cayetanobv/QGIS
    def __init__(self, row, table):
        TableField.__init__(self, table)
        self.num, self.name, self.dataType, self.charMaxLen, self.modifier, self.notNull, self.hasDefault, self.default, typeStr = row
        self.primaryKey = False

        # get modifier (e.g. "precision,scale") from formatted type string
        trimmedTypeStr = typeStr.strip()
        regex = QRegExp("\((.+)\)$")
        startpos = regex.indexIn(trimmedTypeStr)
        if startpos >= 0:
            self.modifier = regex.cap(1).strip()
        else:
            self.modifier = None

        # find out whether fields are part of primary key
        for con in self.table().constraints():
            if con.type == TableConstraint.TypePrimaryKey and self.num in con.columns:
                self.primaryKey = True
                break
コード例 #34
0
ファイル: XMLHighlighter.py プロジェクト: 3liz/QuickOSM
    def highlightBlock(self, text):
        # 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)

        self.setCurrentBlockState(0)

        start_index = 0
        if self.previousBlockState() != 1:
            start_index = self.value_start_expression.indexIn(text)

        while start_index >= 0:
            end_index = self.value_end_expression.indexIn(text, start_index)

            if end_index == -1:
                self.setCurrentBlockState(1)
                comment_length = len(text) - start_index
            else:
                comment_length = \
                    end_index - start_index + \
                    self.value_end_expression.matchedLength()

            self.setFormat(start_index, comment_length, self.value_format)

            start_index = self.value_start_expression.indexIn(
                text, start_index + comment_length)
コード例 #35
0
ファイル: XMLHighlighter.py プロジェクト: 3liz/QuickOSM
    def __init__(self, parent=None):
        super(XMLHighlighter, self).__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]

        xml_element_format = QTextCharFormat()
        xml_element_format.setForeground(QColor("#117700"))
        self.highlightingRules.append(
            (QRegExp("\\b[A-Za-z0-9_\-]+(?=[\s/>])"), xml_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))

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

        self.value_format = QTextCharFormat()
        self.value_format.setForeground(Qt.red)

        self.value_start_expression = QRegExp("\"")
        self.value_end_expression = QRegExp("\"(?=[\s></])")

        single_line_comment_format = QTextCharFormat()
        single_line_comment_format.setForeground(Qt.gray)
        self.highlightingRules.append(
            (QRegExp("<!--[^\n]*-->"), single_line_comment_format))
コード例 #36
0
ファイル: XMLHighlighter.py プロジェクト: 3liz/QuickOSM
class XMLHighlighter(QSyntaxHighlighter):

    def __init__(self, parent=None):
        super(XMLHighlighter, self).__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]

        xml_element_format = QTextCharFormat()
        xml_element_format.setForeground(QColor("#117700"))
        self.highlightingRules.append(
            (QRegExp("\\b[A-Za-z0-9_\-]+(?=[\s/>])"), xml_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))

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

        self.value_format = QTextCharFormat()
        self.value_format.setForeground(Qt.red)

        self.value_start_expression = QRegExp("\"")
        self.value_end_expression = QRegExp("\"(?=[\s></])")

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

    def highlightBlock(self, text):
        # 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)

        self.setCurrentBlockState(0)

        start_index = 0
        if self.previousBlockState() != 1:
            start_index = self.value_start_expression.indexIn(text)

        while start_index >= 0:
            end_index = self.value_end_expression.indexIn(text, start_index)

            if end_index == -1:
                self.setCurrentBlockState(1)
                comment_length = len(text) - start_index
            else:
                comment_length = \
                    end_index - start_index + \
                    self.value_end_expression.matchedLength()

            self.setFormat(start_index, comment_length, self.value_format)

            start_index = self.value_start_expression.indexIn(
                text, start_index + comment_length)