def __init__(self, show_strength=True, parent=None): super(PinMatrixWidget, self).__init__(parent) self.password = QLineEdit() self.password.setValidator(QRegExpValidator(QRegExp('[1-9]+'), None)) self.password.setEchoMode(QLineEdit.Password) QObject.connect(self.password, SIGNAL('textChanged(QString)'), self._password_changed) self.strength = QLabel() self.strength.setMinimumWidth(75) self.strength.setAlignment(Qt.AlignCenter) self._set_strength(0) grid = QGridLayout() grid.setSpacing(0) for y in range(3)[::-1]: for x in range(3): button = PinButton(self.password, x + y * 3 + 1) button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) button.setFocusPolicy(Qt.NoFocus) grid.addWidget(button, 3 - y, x) hbox = QHBoxLayout() hbox.addWidget(self.password) if show_strength: hbox.addWidget(self.strength) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addLayout(hbox) self.setLayout(vbox)
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 (*.dbf)')) 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') for ext in ['.dbf']: QFile(tempbase + ext).copy(ofbase + ext) fb = QgsVectorLayer(ofbase + '.dbf', QFileInfo(ofbase).baseName(), "ogr") if fb.isValid(): QgsMapLayerRegistry.instance().addMapLayer(fb)
def __init__(self): QPlainTextEdit.__init__(self, u'>>> ') self.setUndoRedoEnabled(False) self.apply_editor_style() self.setToolTip(self.tr("Show/Hide (F4)")) self.moveCursor(QTextCursor.EndOfLine) self._patIsWord = re.compile('\w+') self.prompt = u'>>> ' self._console = console.Console() self._history = [] self._braces = None self.imports = ['import __builtin__'] self.patFrom = re.compile('^(\\s)*from ((\\w)+(\\.)*(\\w)*)+ import') self.patImport = re.compile('^(\\s)*import (\\w)+') self.patObject = re.compile('[^a-zA-Z0-9_\\.]') self.completer = completer_widget.CompleterWidget(self) self.okPrefix = QRegExp('[.)}:,\]]') #Create Context Menu self._create_context_menu() self._highlighter = highlighter.Highlighter(self.document(), 'python', resources.CUSTOM_SCHEME) self.connect(self, SIGNAL("cursorPositionChanged()"), self.highlight_current_line) self.highlight_current_line() self._proc = QProcess(self) self.connect(self._proc, SIGNAL("readyReadStandardOutput()"), self._python_path_detected) self.connect(self._proc, SIGNAL("error(QProcess::ProcessError)"), self.process_error) self._add_system_path_for_frozen()
def __init__(self, file_name): super(Login, self).__init__() Pictures.getpicture(os.getcwd() + "\\resource") self.setWindowIcon(QIcon(Pictures.appfilename)) #self.appconfg = APPConfigparse.APPConfigparse('./config.ini') config_name = file_name self.appconfg = APPConfigparse.APPConfigparse(config_name) self.txt_name.setText(self.appconfg.UserName) print Pictures.backfilename background = QPixmap(Pictures.backfilename) background = background.scaled(self.lab_back.width(), self.lab_back.width()) self._init_ui() self.lab_back.setPixmap(background) self.txt_pwd.setEchoMode(QLineEdit.Password) self.txt_pwd.setMaxLength(8) self.txt_pwd.setContextMenuPolicy( Qt.NoContextMenu) # 这个语句设置QLineEdit对象的上下文菜单的策略。复制,粘贴,。。。,是否可用 self.txt_pwd.setPlaceholderText( u"密码不超8位数字和字母组成" ) # 只要行编辑为空,设置此属性将使行编辑显示为灰色的占位符文本。默认情况下,此属性包含一个空字符串。这是非常 # regx = QRegExp("^[a-zA-Z][0-9A-Za-z]{8}") # 为给定的模式字符串构造一个正则表达式对象。 regx = QRegExp("^[0-9][0-9A-Za-z]{8}") # 为给定的模式字符串构造一个正则表达式对象。 validator = QRegExpValidator(regx, self.txt_pwd) # 构造一个验证器 self.txt_pwd.setValidator(validator) # 数据输入验证器 self.btnOK.clicked.connect(self._btnok) self.btn_cancel.clicked.connect(self._btncancel) self.chk_debug.clicked.connect(self._chk_debug_click)
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) # creating progress dialog for download self.progress_dialog = QProgressDialog(self) self.progress_dialog.setAutoClose(False) self.progress_dialog.setWindowTitle(title) # Set up things for context help self.help_button = self.button_box.button(QtGui.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 = QRegExpValidator(expression, self.filename_prefix) self.filename_prefix.setValidator(validator) self.time_stamp = None self.restore_state()
def _replace_results(self): result = QMessageBox.question( self, self.tr("Replace Files Contents"), self.tr("Are you sure you want to replace the content in " "this files?\n(The change is not reversible)"), buttons=QMessageBox.Yes | QMessageBox.No) if result == QMessageBox.Yes: for index in xrange(self._result_widget.topLevelItemCount()): parent = self._result_widget.topLevelItem(index) root_dir_name = unicode(parent.dir_name_root) file_name = unicode(parent.text(0)) file_path = file_manager.create_path(root_dir_name, file_name) file_object = QFile(file_path) if not file_object.open(QFile.ReadOnly): return stream = QTextStream(file_object) content = stream.readAll() file_object.close() pattern = self._find_widget.pattern_line_edit.text() case_sensitive = self._find_widget.case_checkbox.isChecked() type_ = QRegExp.RegExp if \ self._find_widget.type_checkbox.isChecked() else \ QRegExp.FixedString target = QRegExp(pattern, case_sensitive, type_) content.replace(target, self._find_widget.replace_line.text()) file_manager.store_file_content(file_path, content, False)
def run(self): """Execute this rules in another thread to avoid blocking the ui.""" styles = {} self.msleep(300) block = self._highlighter.document().begin() while block.blockNumber() != -1: text = block.text() formats = [] for expression, nth, char_format in self._highlighter.rules: index = expression.indexIn(text, 0) while index >= 0: # We actually want the index of the nth match index = expression.pos(nth) length = len(expression.cap(nth)) formats.append((index, length, char_format)) index = expression.indexIn(text, index + length) #Spaces expression = QRegExp('\s+') index = expression.indexIn(text, 0) while index >= 0: index = expression.pos(0) length = len(expression.cap(0)) formats.append((index, length, STYLES['spaces'])) index = expression.indexIn(text, index + length) styles[block.blockNumber()] = formats block = block.next() self.emit(SIGNAL("highlightingDetected(PyQt_PyObject)"), styles)
def replace(self, what, new, *args): """Replace the first occurence of a search arg[0] -> QTextDocument.FindCaseSensitively arg[1] -> QTextDocument.FindWholeWords arg[2] -> QTextDocument.FindBackward arg[3] -> QTextDocument.RegEx """ # Use flags for case match flags = QTextDocument.FindFlags() if args[0]: flags = flags | QTextDocument.FindCaseSensitively if args[1]: flags = flags | QTextDocument.FindWholeWords if args[2]: flags = flags | QTextDocument.FindBackward # Beginning of undo block pcursor = self.textCursor() pcursor.beginEditBlock() cursor = self.textCursor() # Replace # self is the QTextEdit if args[3] == True: cursor = self.document().find(QRegExp(what), cursor, flags) else: cursor = self.document().find(what, cursor, flags) if not cursor.isNull(): if cursor.hasSelection(): cursor.insertText(new) # Mark end of undo block pcursor.endEditBlock()
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: 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 highlightBlock(self, text): for pattern, format in self.rules: exp = QRegExp(pattern) index = exp.indexIn(text) while index >= 0: length = exp.matchedLength() if exp.numCaptures() > 0: self.setFormat(exp.pos(1), len(str(exp.cap(1))), format) else: self.setFormat(exp.pos(0), len(str(exp.cap(0))), format) index = exp.indexIn(text, index + length) # Multi line strings start = self.multilineStart end = self.multilineEnd self.setCurrentBlockState(0) startIndex, skip = 0, 0 if self.previousBlockState() != 1: startIndex, skip = start.indexIn(text), 3 while startIndex >= 0: endIndex = end.indexIn(text, startIndex + skip) if endIndex == -1: self.setCurrentBlockState(1) commentLen = len(text) - startIndex else: commentLen = endIndex - startIndex + 3 self.setFormat(startIndex, commentLen, self.stringFormat) startIndex, skip = (start.indexIn(text, startIndex + commentLen + 3), 3)
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 goToPage(self): tc = self.document().find(QString(u'['), self.textCursor(), QTextDocument.FindBackward) if not tc.isNull(): # found it, or one. tc now selects the [ re = QRegExp(QString(u'\[\d+\]')) tc.setPosition(tc.selectionStart()) # start looking left of [ tc = self.document().find(re, tc) if not tc.isNull(): # found that. self.setTextCursor(tc) # highlight the found string qs = tc.selectedText() # "[nnn]" qs.remove(0, 1) # "nnn]" qs.chop(1) # "nnn" (pn, flg) = qs.toInt() # page number as int pn -= 1 # index to that page in the page table if (pn >= 0) and (pn < IMC.pageTable.size()): etc = IMC.pageTable.getCursor(pn) # cursor for that page doc = IMC.editWidget.document() # main document IMC.editWidget.setTextCursor(etc) # make it visible IMC.editWidget.setFocus(Qt.TabFocusReason) else: # should not occur pqMsgs.beep() else: # no [ppp] seen pqMsgs.beep() else: # no [ preceding the cursor on same line pqMsgs.beep()
def __init__(self, parent=None): super(NewEntryDialog, self).__init__(parent) loadUi(__file__, self) # General window settings self.monthTab = parent.currentMonthTab() self.setWindowTitle('New Entry for \'%s\'' % self.monthTab.month()) self.setFixedSize(self.size()) # Entry name LineEdit settings strValidator = QRegExpValidator(QRegExp('.+')) self.nameLineEdit.setValidator(strValidator) completer = QCompleter(self.monthTab.entriesStringList()) completer.setCaseSensitivity(Qt.CaseInsensitive) self.nameLineEdit.setCompleter(completer) # DateEdit settings date = QDate(parent.year(), self.monthTab.monthIndex() + 1, 1) self.dateEdit.setDateRange( date, QDate(date.year(), date.month(), date.daysInMonth())) self.dateEdit.setDate(date) self.dateEdit.setCalendarPopup(True) self.dateEdit.calendarWidget().setFirstDayOfWeek(Qt.Monday) # CategoryComboBox settings self.categoryComboBox.setModel(self.monthTab.categoriesModel()) # OK PushButton settings self.okButton = self.buttonBox.button(QDialogButtonBox.Ok) self.okButton.setEnabled(False) # CONNECTIONS self.nameLineEdit.textEdited.connect(self.setOKButton)
def highlightBlock(self, text): """Apply syntax highlighting to the given block of text.""" for expression, nth, format in self.rules: index = expression.indexIn(text, 0) while index >= 0: # We actually want the index of the nth match index = expression.pos(nth) length = expression.cap(nth).length() self.setFormat(index, length, format) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0) if not self.multi_start: # Do multi-line strings in_multiline = self.match_multiline(text, *self.tri_single) if not in_multiline: in_multiline = self.match_multiline(text, *self.tri_double) else: # Do multi-line comment self.comment_multiline(text, self.multi_end[0], *self.multi_start) #Spaces expression = QRegExp('\s+') index = expression.indexIn(text, 0) while index >= 0: index = expression.pos(0) length = expression.cap(0).length() self.setFormat(index, length, STYLES['spaces']) index = expression.indexIn(text, index + length)
def find(self, what, *args): """Perform a search arg[0] -> QTextDocument.FindCaseSensitively arg[1] -> QTextDocument.FindWholeWords arg[2] -> QTextDocument.FindBackward arg[3] -> QTextDocument.RegEx """ print 'find called' # Use flags for case match flags = QTextDocument.FindFlags() if args[0] == True: flags = flags | QTextDocument.FindCaseSensitively if args[1] == True: flags = flags | QTextDocument.FindWholeWords if args[2] == True: flags = flags | QTextDocument.FindBackward cursor = self.textCursor() if args[3] == True: cursor = self.document().find(QRegExp(what), cursor, flags) else: cursor = self.document().find(what, cursor, flags) if not cursor.isNull(): self.setTextCursor(cursor)
def highlightBlock(self, text): #for every pattern for pattern, 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, format) #Set index to where the expression ends in the text index = expression.indexIn(text, index + length) #HANDLE QUOTATION MARKS NOW.. WE WANT TO START WITH " AND END WITH ".. A THIRD " SHOULD NOT CAUSE THE WORDS INBETWEEN SECOND AND THIRD TO BE COLORED self.setCurrentBlockState(0) startIndex = 0 if self.previousBlockState() != 1: startIndex = self.valueStartExpression.indexIn(text) while startIndex >= 0: endIndex = self.valueEndExpression.indexIn(text, startIndex) if endIndex == -1: self.setCurrentBlockState(1) commentLength = len(text) - startIndex else: commentLength = endIndex - startIndex + self.valueEndExpression.matchedLength( ) self.setFormat(startIndex, commentLength, self.valueFormat) startIndex = self.valueStartExpression.indexIn( text, startIndex + commentLength)
def __init__(self, parent=None, default_value=0): QSpinBox.__init__(self, parent) self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self) self.setRange(0, 255) self.setValue(default_value)
def set_selected_word(self, word): """Set the word to highlight.""" if len(word) > 2: self.selected_word_pattern = QRegExp(r'\b%s\b' % self.sanitize(word)) else: self.selected_word_pattern = None
def __init__(self): super(ConsoleWidget, self).__init__('>>> ') self.setUndoRedoEnabled(False) self.apply_editor_style() self.setToolTip(self.tr("Show/Hide (F4)")) self.moveCursor(QTextCursor.EndOfLine) self._patIsWord = re.compile('\w+') self.prompt = '>>> ' self._console = console.Console() self._history = [] self.history_index = 0 self._current_command = '' self._braces = None self.imports = ['import __builtin__'] self.patFrom = re.compile('^(\\s)*from ((\\w)+(\\.)*(\\w)*)+ import') self.patImport = re.compile('^(\\s)*import (\\w)+') self.patObject = re.compile('[^a-zA-Z0-9_\\.]') #self.completer = completer_widget.CompleterWidget(self) self.okPrefix = QRegExp('[.)}:,\]]') self._pre_key_press = { Qt.Key_Enter: self._enter_pressed, Qt.Key_Return: self._enter_pressed, Qt.Key_Tab: self._tab_pressed, Qt.Key_Home: self._home_pressed, Qt.Key_PageUp: lambda x: True, Qt.Key_PageDown: lambda x: True, Qt.Key_Left: self._left_pressed, Qt.Key_Up: self._up_pressed, Qt.Key_Down: self._down_pressed, Qt.Key_Backspace: self._backspace, } #Create Context Menu self._create_context_menu() #Set Font self.set_font(settings.FONT) #Create Highlighter parts_scanner, code_scanner, formats = \ syntax_highlighter.load_syntax(python_syntax.syntax) self.highlighter = syntax_highlighter.SyntaxHighlighter( self.document(), parts_scanner, code_scanner, formats) self.connect(self, SIGNAL("cursorPositionChanged()"), self.highlight_current_line) self.highlight_current_line() self._proc = QProcess(self) self.connect(self._proc, SIGNAL("readyReadStandardOutput()"), self._python_path_detected) self.connect(self._proc, SIGNAL("error(QProcess::ProcessError)"), self.process_error) self._add_system_path_for_frozen() ninjaide = IDE.get_service('ide') self.connect(ninjaide, SIGNAL("ns_preferences_editor_font(PyQt_PyObject)"), self.set_font)
def set_selected_word(self, word, partial=True): """Set the word to highlight.""" # partial = True for new highlighter compatibility hl_worthy = len(word) > 2 if hl_worthy: self.selected_word_pattern = QRegExp(r'\b%s\b' % self.sanitize(word)) else: self.selected_word_pattern = None suffix = "(?![A-Za-z_\d])" prefix = "(?<![A-Za-z_\d])" word = re.escape(word) if not partial: word = "%s%s%s" % (prefix, word, suffix) lines = [] pat_find = re.compile(word) document = self.document() for lineno, text in enumerate(document.toPlainText().splitlines()): if hl_worthy and pat_find.search(text): lines.append(lineno) elif self._old_search and self._old_search.search(text): lines.append(lineno) # Ask perrito if i don't know what the next line does: self._old_search = hl_worthy and pat_find self.rehighlight_lines(lines)
def popup(self, pos=None, searchText=""): """ Popup the menu at `pos` (in screen coordinates). 'Search' text field is initialized with `searchText` if provided. """ if pos is None: pos = QPoint() self.__clearCurrentItems() self.__search.setText(searchText) patt = QRegExp("(^|\W)" + searchText) patt.setCaseSensitivity(False) self.__suggestPage.setFilterRegExp(patt) self.ensurePolished() if self.testAttribute(Qt.WA_Resized) and self.sizeGripEnabled(): size = self.size() else: size = self.sizeHint() desktop = QApplication.desktop() screen_geom = desktop.availableGeometry(pos) # Adjust the size to fit inside the screen. if size.height() > screen_geom.height(): size.setHeight(screen_geom.height()) if size.width() > screen_geom.width(): size.setWidth(screen_geom.width()) geom = QRect(pos, size) if geom.top() < screen_geom.top(): geom.setTop(screen_geom.top()) if geom.left() < screen_geom.left(): geom.setLeft(screen_geom.left()) bottom_margin = screen_geom.bottom() - geom.bottom() right_margin = screen_geom.right() - geom.right() if bottom_margin < 0: # Falls over the bottom of the screen, move it up. geom.translate(0, bottom_margin) # TODO: right to left locale if right_margin < 0: # Falls over the right screen edge, move the menu to the # other side of pos. geom.translate(-size.width(), 0) self.setGeometry(geom) self.show() if searchText: self.setFocusProxy(self.__search) else: self.setFocusProxy(None)
def on_createConfig_clicked(self): toolname = str(self.test_line[0].text()) if (len(toolname) < 1): self.test_line[0].setText('must specify configuration name') self.test_line[0].selectAll() self.test_line[0].setFocus() return newNode = Element('tool_config', {'name': toolname}) newChild = SubElement(newNode, 'tool_hook', { 'hidden': 'True', }) newChild.text = str(self.typeSelection) # for key,val in self.vars.iteritems(): for x in xrange(1, len(self.test_text)): #self.vars[self.test_text[x].text()] = self.test_line[x].text() if type(self.test_line[x]) == QComboBox: key = self.test_text[x].text() val = self.test_line[x].currentText() else: key = self.test_text[x].text() val = self.test_line[x].text() typeVal = self.test_text_type[x].text().remove(QRegExp("[\(\)]")) SubElement(newNode, str(key)).text = str(val) self.callback(newNode) self.close()
def goToLine(self): tc = self.document().find(QString(u'{'), self.textCursor(), QTextDocument.FindBackward) if not tc.isNull(): # found it, or one. tc now selects the { re = QRegExp(QString(u'\{\d+\}')) tc.setPosition(tc.selectionStart()) # start looking left of { tc = self.document().find(re, tc) if not tc.isNull(): # found that. self.setTextCursor(tc) # highlight the found string qs = tc.selectedText() # "{nnn}" qs.remove(0, 1) # "nnn}" qs.chop(1) # "nnn" # toInt returns a tuple, (int, flag) where flag is false # if the conversion fails. In this case it cannot fail # since we found \d+ in the first place. However, the # number might be invalid as a line number. (bn, flg) = qs.toInt() # line number as int doc = IMC.editWidget.document() # main document tb = doc.findBlockByNumber(bn) # text block number bn if tb.isValid(): # if it exists, tc = IMC.editWidget.textCursor() # cursor on main doc tc.setPosition(tb.position()) # set it on block IMC.editWidget.setTextCursor(tc) # make it visible IMC.editWidget.setFocus(Qt.TabFocusReason) else: # no {ddd} seen pqMsgs.beep() else: # no { preceding the cursor on same line pqMsgs.beep()
def __init__(self, document): QSyntaxHighlighter.__init__(self, document) # 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 = [] # Keyword, operator, and brace rules rules += [(r'\b%s\b' % w, 0, STYLES['keyword']) for w in PythonHighlighter.keywords] rules += [(r'%s' % o, 0, STYLES['operator']) for o in PythonHighlighter.operators] rules += [(r'%s' % b, 0, STYLES['brace']) for b in PythonHighlighter.braces] # 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'\bdef\b\s*(\w+)', 1, STYLES['defclass']), # 'class' followed by an identifier (r'\bclass\b\s*(\w+)', 1, STYLES['defclass']), # 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']), ] # Build a QRegExp for each pattern self.rules = [(QRegExp(pat), index, fmt) for (pat, index, fmt) in rules]
def __init__(self, parent=None, fixed_size=40, regex=r'.+', placeholder=None): super(InputCustomPattern, self).__init__(parent=parent) if placeholder: self.setPlaceholderText(placeholder) self.setFixedWidth(fixed_size) validator = QRegExpValidator(QRegExp(regex), self) self.setValidator(validator)
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)
def end_keywordlist(self): rules = [(r'\b%s\b' % w, 0, self.get_style(self.__style)) for w in self.__keywords] self._grammar += ([(QRegExp(pat), index, fmt) for (pat, index, fmt) in rules]) del self.__keywords del self.__style del self.__flags
def findcontrol(self, name): regex = QRegExp("^{}$".format(name)) regex.setCaseSensitivity(Qt.CaseInsensitive) try: widget = self.findChildren(QWidget, regex)[0] except IndexError: widget = None return widget
def __init__(self, parent=None): super(RomanSpinBox, self).__init__(parent) regex = QRegExp(r"^M?M?M?(?:CM|CD|D?C?C?C?)" r"(?:XC|XL|L?X?X?X?)(?:IX|IV|V?I?I?I?)$") regex.setCaseSensitivity(Qt.CaseInsensitive) self.validator = QRegExpValidator(regex, self) self.setRange(1, 3999) self.lineEdit().textEdited.connect(self.fixCase)
def __init__(self, parent=None, iface=None): """Constructor for import dialog. :param parent: Optional widget to use as parent :type parent: QWidget :param iface: An instance of QGisInterface :type iface: QGisInterface """ QDialog.__init__(self, parent) self.parent = parent self.setupUi(self) self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader')) self.iface = iface self.buildings_url = 'http://osm.linfiniti.com/buildings-shp' self.building_points_url = \ 'http://osm.linfiniti.com/building-points-shp' self.roads_url = 'http://osm.linfiniti.com/roads-shp' self.help_context = 'openstreetmap_downloader' # creating progress dialog for download self.progress_dialog = QProgressDialog(self) self.progress_dialog.setAutoClose(False) title = self.tr('InaSAFE OpenStreetMap Downloader') self.progress_dialog.setWindowTitle(title) # Set up context help help_button = self.button_box.button(QtGui.QDialogButtonBox.Help) help_button.clicked.connect(self.show_help) self.show_info() # set up the validator for the file name prefix expression = QRegExp('^[A-Za-z0-9-_]*$') validator = QRegExpValidator(expression, self.filename_prefix) self.filename_prefix.setValidator(validator) # Set Proxy in webpage proxy = get_proxy() self.network_manager = QNetworkAccessManager(self) if proxy is not None: self.network_manager.setProxy(proxy) self.restore_state() # Setup the rectangle map tool self.canvas = iface.mapCanvas() self.rectangle_map_tool = \ RectangleMapTool(self.canvas) self.rectangle_map_tool.rectangle_created.connect( self.update_extent_from_rectangle) self.button_extent_rectangle.clicked.connect( self.drag_rectangle_on_map_canvas) # Setup pan tool self.pan_tool = QgsMapToolPan(self.canvas) self.canvas.setMapTool(self.pan_tool) self.update_extent_from_map_canvas()