我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用PyQt5.QtCore.QRegExp()。
def __init__(self, min_, max_, float_=False): super(QwordSpinBox, self).__init__() self._minimum = min_ self._maximum = max_ self.int_ = float if float_ else int rx = QRegExp('-?\d{0,20}(?:\.\d{0,20})?' if float_ else '-?\d{0,20}') validator = QRegExpValidator(rx, self) self._lineEdit = QLineEdit(self) self._lineEdit.setText(str(self.int_(0))) self._lineEdit.setValidator(validator) self._lineEdit.textEdited.connect(partial(self.setValue, change=False)) self.editingFinished.connect(lambda: self.setValue(self.value(), update=False) or True) self.setLineEdit(self._lineEdit)
def __init__(self, parent=None): self.keywordFormat = self._text_format(Qt.blue) self.stringFormat = self._text_format(Qt.darkRed) self.commentFormat = self._text_format(Qt.darkGreen) self.decoratorFormat = self._text_format(Qt.darkGray) self.keywords = list(keyword_list) self.rules = [(QRegExp(r"\b%s\b" % kwd), self.keywordFormat) for kwd in self.keywords] + \ [(QRegExp(r"'.*'"), self.stringFormat), (QRegExp(r'".*"'), self.stringFormat), (QRegExp(r"#.*"), self.commentFormat), (QRegExp(r"@[A-Za-z_]+[A-Za-z0-9_]+"), self.decoratorFormat)] self.multilineStart = QRegExp(r"(''')|" + r'(""")') self.multilineEnd = QRegExp(r"(''')|" + r'(""")') super().__init__(parent)
def encodingChanged(self, idx): encoding = str(self.mode_combo.currentText()) validator = None if encoding == 'hex': # only clear the box if there are non-hex chars # before setting the validator. txt = str(self.data_edit.text()) if not all(c in string.hexdigits for c in txt): self.data_edit.setText('') regex = QtCore.QRegExp('^[0-9A-Fa-f]+$') validator = QtWidgets.QRegExpValidator(regex) self.data_edit.setValidator(validator) txt = str(self.data_edit.text()) txt_encoded = self.encodeData(txt, encoding) self.updateHexPreview(txt_encoded)
def encodingChanged(self, idx): encoding = str(self.mode_combo.currentText()) validator = None if encoding == 'hex': # only clear the box if there are non-hex chars # before setting the validator. txt = str(self.data_edit.text()) if not all(c in string.hexdigits for c in txt): self.data_edit.setText('') regex = QtCore.QRegExp('^[0-9A-Fa-f]+$') validator = QtWidgets.QRegExpValidator(regex) self.data_edit.setValidator(validator) self.renderMemory()
def initializePage(self): className = self.field('className') self.macroNameLineEdit.setText(className.upper() + "_H") baseClass = self.field('baseClass') is_baseClass = bool(baseClass) self.includeBaseCheckBox.setChecked(is_baseClass) self.includeBaseCheckBox.setEnabled(is_baseClass) self.baseIncludeLabel.setEnabled(is_baseClass) self.baseIncludeLineEdit.setEnabled(is_baseClass) if not is_baseClass: self.baseIncludeLineEdit.clear() elif QRegExp('Q[A-Z].*').exactMatch(baseClass): self.baseIncludeLineEdit.setText('<' + baseClass + '>') else: self.baseIncludeLineEdit.setText('"' + baseClass.lower() + '.h"')
def __init__(self, parent=None): super(StyleSheetEditor, self).__init__(parent) self.ui = Ui_StyleSheetEditor() self.ui.setupUi(self) regExp = QRegExp(r'.(.*)\+?Style') defaultStyle = QApplication.style().metaObject().className() if regExp.exactMatch(defaultStyle): defaultStyle = regExp.cap(1) self.ui.styleCombo.addItems(QStyleFactory.keys()) self.ui.styleCombo.setCurrentIndex( self.ui.styleCombo.findText(defaultStyle, Qt.MatchContains)) self.ui.styleSheetCombo.setCurrentIndex( self.ui.styleSheetCombo.findText('Coffee')) self.loadStyleSheet('Coffee')
def __init__(self, checksum_label: ChecksumLabel, message: Message, proto_view: int, parent=None): super().__init__(parent) self.ui = Ui_ChecksumOptions() self.ui.setupUi(self) self.checksum_label = checksum_label self.data_range_table_model = self.RangeTableModel(checksum_label, message, proto_view, parent=self) self.ui.tableViewDataRanges.setItemDelegateForColumn(0, SpinBoxDelegate(1, 999999, self)) self.ui.tableViewDataRanges.setItemDelegateForColumn(1, SpinBoxDelegate(1, 999999, self)) self.ui.tableViewDataRanges.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.ui.tableViewDataRanges.setModel(self.data_range_table_model) self.ui.tableViewDataRanges.setEditTriggers(QAbstractItemView.AllEditTriggers) self.display_crc_data_ranges_in_table() self.ui.comboBoxCRCFunction.addItems([crc_name for crc_name in GenericCRC.DEFAULT_POLYNOMIALS]) self.ui.comboBoxCRCFunction.addItems([special_crc_name for special_crc_name in self.SPECIAL_CRCS]) self.ui.lineEditCRCPolynomial.setValidator(QRegExpValidator(QRegExp("[0-9,a-f]*"))) self.ui.comboBoxCategory.clear() for _, member in self.checksum_label.Category.__members__.items(): self.ui.comboBoxCategory.addItem(member.value) self.set_ui_for_category() self.setFocus() self.create_connects()
def dialog_ui(self) -> QDialog: if self.__dialog_ui is None: dir_name = os.path.dirname(os.readlink(__file__)) if os.path.islink(__file__) else os.path.dirname(__file__) self.__dialog_ui = uic.loadUi(os.path.realpath(os.path.join(dir_name, "insert_sine_dialog.ui"))) self.__dialog_ui.setAttribute(Qt.WA_DeleteOnClose) self.__dialog_ui.setModal(True) self.__dialog_ui.doubleSpinBoxAmplitude.setValue(self.__amplitude) self.__dialog_ui.doubleSpinBoxFrequency.setValue(self.__frequency) self.__dialog_ui.doubleSpinBoxPhase.setValue(self.__phase) self.__dialog_ui.doubleSpinBoxSampleRate.setValue(self.__sample_rate) self.__dialog_ui.doubleSpinBoxNSamples.setValue(self.__num_samples) self.__dialog_ui.lineEditTime.setValidator( QRegExpValidator(QRegExp("[0-9]+([nmµ]*|([\.,][0-9]{1,3}[nmµ]*))?$"))) scene_manager = SceneManager(self.dialog_ui.graphicsViewSineWave) self.__dialog_ui.graphicsViewSineWave.scene_manager = scene_manager self.insert_indicator = scene_manager.scene.addRect(0, -2, 0, 4, QPen(QColor(Qt.transparent), Qt.FlatCap), QBrush(self.INSERT_INDICATOR_COLOR)) self.insert_indicator.stackBefore(scene_manager.scene.selection_area) self.set_time() return self.__dialog_ui
def OnPackageNameChanged(self, text): search = QtCore.QRegExp(text,QtCore.Qt.CaseInsensitive,QtCore.QRegExp.RegExp) self.package_list_proxy.setFilterRegExp(search)
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.captureCount() > 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 __init__(self, parent = None): QDoubleSpinBox.__init__(self, parent) self.saved_suffix = '' #Let's use the locale decimal separator if it is different from the dot ('.') local_decimal_separator = QLocale().decimalPoint() if local_decimal_separator == '.': local_decimal_separator = '' self.lineEdit().setValidator(QRegExpValidator(QRegExp("-?[0-9]*[.{0}]?[0-9]*.*".format(local_decimal_separator)), self))
def __init__(self, parent=None): super(XmlSyntaxHighlighter, self).__init__(parent) self.highlightingRules = [] # Tag format. format = QTextCharFormat() format.setForeground(Qt.darkBlue) format.setFontWeight(QFont.Bold) pattern = QRegExp("(<[a-zA-Z:]+\\b|<\\?[a-zA-Z:]+\\b|\\?>|>|/>|</[a-zA-Z:]+>)") self.highlightingRules.append((pattern, format)) # Attribute format. format = QTextCharFormat() format.setForeground(Qt.darkGreen) pattern = QRegExp("[a-zA-Z:]+=") self.highlightingRules.append((pattern, format)) # Attribute content format. format = QTextCharFormat() format.setForeground(Qt.red) pattern = QRegExp("(\"[^\"]*\"|'[^']*')") self.highlightingRules.append((pattern, format)) # Comment format. self.commentFormat = QTextCharFormat() self.commentFormat.setForeground(Qt.lightGray) self.commentFormat.setFontItalic(True) self.commentStartExpression = QRegExp("<!--") self.commentEndExpression = QRegExp("-->")
def highlightBlock(self, text): for pattern, format in self.highlightingRules: expression = QRegExp(pattern) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, format) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0) startIndex = 0 if self.previousBlockState() != 1: startIndex = self.commentStartExpression.indexIn(text) while startIndex >= 0: endIndex = self.commentEndExpression.indexIn(text, startIndex) if endIndex == -1: self.setCurrentBlockState(1) commentLength = text.length() - startIndex else: commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength() self.setFormat(startIndex, commentLength, self.commentFormat) startIndex = self.commentStartExpression.indexIn(text, startIndex + commentLength)
def highlightBlock(self, text): for pattern, format in self.highlightingRules: expression = QRegExp(pattern) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, format) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0) startIndex = 0 if self.previousBlockState() != 1: startIndex = self.commentStartExpression.indexIn(text) while startIndex >= 0: endIndex = self.commentEndExpression.indexIn(text, startIndex) if endIndex == -1: self.setCurrentBlockState(1) commentLength = len(text) - startIndex else: commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength() self.setFormat(startIndex, commentLength, self.multiLineCommentFormat) startIndex = self.commentStartExpression.indexIn(text, startIndex + commentLength);
def valueFromText(text): regExp = QRegExp("(\\d+)(\\s*[xx]\\s*\\d+)?") if regExp.exactMatch(text): return int(regExp.cap(1)) else: return 0
def isSummary(self, text): re = QRegExp("(In )?((The|This) )?(%s )?.*(tutorial|example|demo|application)" % self.name, Qt.CaseInsensitive) return ('[' not in text) and (re.indexIn(text) >= 0)
def set_allow_negative(self, allow): self._allow_negative = allow if allow: self.setInputMask('X9:99:99.999') self.setValidator( QtGui.QRegExpValidator( QtCore.QRegExp(r'[+-]\d:\d\d:\d\d\.\d\d\d'), self.parent())) else: self.setInputMask('9:99:99.999') self.reset_text()
def validate(self, inpt: str, pos: int): rx = QRegExp("^(-?[0-9]+)[.]?[0-9]*[kKmMgG]?$") result = QValidator.Acceptable if rx.exactMatch(inpt.replace(",", ".")) else QValidator.Invalid return result, inpt, pos
def highlight_slipfactor_description(self): """Highlight the description of currosponding slipfactor on selection of inputs Note : This routine is not in use in current version :return: """ slip_factor = str(self.ui.combo_slipfactor.currentText()) self.textCursor = QTextCursor(self.ui.textBrowser.document()) cursor = self.textCursor # Setup the desired format for matches format = QTextCharFormat() format.setBackground(QBrush(QColor("red"))) # Setup the regex engine pattern = str(slip_factor) regex = QRegExp(pattern) # Process the displayed document pos = 0 index = regex.indexIn(self.ui.textBrowser.toPlainText(), pos) while (index != -1): # Select the matched text and apply the desired format cursor.setPosition(index) cursor.movePosition(QTextCursor.EndOfLine, 1) # cursor.movePosition(QTextCursor.EndOfWord, 1) cursor.mergeCharFormat(format) # Move to the next match pos = index + regex.matchedLength() index = regex.indexIn(self.ui.textBrowser.toPlainText(), pos)
def __init__(self, document): QSyntaxHighlighter.__init__(self, document) self.triple_single = (QRegExp("\'\'\'"), 1, STYLE['doc_string']) self.triple_double = (QRegExp('\"\"\"'), 2, STYLE['doc_string']) # RULES rules = [] # r'' regular expression # [] used to indicate set of characters # \b matches the empty string, but only at the beginning or end of the word # \w matches any alphanumeric chars and the underscore # \s matches any whitespace char # * causes the resulting regexp to match 0 or more repetitions of the preceding regexp. ab* = a, ab, abb, abbb.. # + causes the resulting regexp to match 1 or more repetitions of the preceding regexp. ab+ = ab, abb, abbbb.. # ? causes the resulting regexp to match 0 or 1 repetitions of the preceding regexp. ab? = a, ab # ^ matches the start of the string, and in multi line mode also matches immediately after each new line # ?: A non-capturing version of regular parentheses # QRegExp, int, STYLE rules += [(r'\b%s\b' % keyword, 0, STYLE['keywords']) for keyword in PythonHighlighter.keywords] rules += [(r'\b%s\b' % boolean, 0, STYLE['booleans']) for boolean in PythonHighlighter.booleans] rules += [(r'%s' % operator, 0, STYLE['operators']) for operator in PythonHighlighter.operators] rules += [(r'%s' % brace, 0, STYLE['braces']) for brace in PythonHighlighter.braces] # Other rules: rules += [ # self (r'\bself\b', 0, STYLE['self']), # string containing double-quote with escape sequence (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLE['string']), # string containing single-quote with escape sequence (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLE['string']), # def/class (r'\bdef\b\s*(\w+)', 1, STYLE['def_class']), (r'\bclass\b\s*(\w+)', 1, STYLE['def_class']), # from # until new-line (r'#[^\n]*', 0, STYLE['comments']), # numbers (r'\b[+-]?[0-9]+[lL]?\b', 0, STYLE['numbers']), (r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b', 0, STYLE['numbers']), # decorator (r'@[^\n', 0, STYLE['def_class']), ] # Build QRegExp for each pattern self.rules = [(QRegExp(pattern), index, fmt) for (pattern, index, fmt) in rules]
def __init__(self): super(addcontact_class, self).__init__() self.setupUi(self) regex_name = QtCore.QRegExp("[a-z-A-Z_]+") name_validator = QtGui.QRegExpValidator(regex_name) self.name_lineEdit.setValidator(name_validator) #self.name_lineEdit = str(self.name_lineEdit.text()) self.phone_lineEdit.setMaxLength(10) regex_phone = QtCore.QRegExp("[0-9_]+") phone_validator = QtGui.QRegExpValidator(regex_phone) self.phone_lineEdit.setValidator(phone_validator) regex_email = QtCore.QRegExp('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$') email_validator = QtGui.QRegExpValidator(regex_email) self.email_lineEdit.setValidator(email_validator) #self.email_lineEdit = str(self.email_lineEdit) #self.address_textEdit = str(self.address_textEdit) self.dob_dateEdit.setDisplayFormat('dd-MM-yyyy') #self.dob_dateEdit.setCalendarPopup(True) self.dob_dateEdit.setDate(QtCore.QDate.currentDate()) temp_dob = self.dob_dateEdit.date() # DOB = temp_dob.toPyDate() DOB =temp_dob.toString('dd/MM/yyyy') print(DOB) self.btn_set_icon.clicked.connect(self.openFileNameDialog) self.btn_save.clicked.connect(self.save_action)
def __init__(self, parent=None): super(Highlighter, self).__init__(parent) keywordFormat = QTextCharFormat() keywordFormat.setForeground(Qt.darkBlue) keywordFormat.setFontWeight(QFont.Bold) keywordPatterns = ["\\bchar\\b", "\\bclass\\b", "\\bconst\\b", "\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b", "\\binline\\b", "\\bint\\b", "\\blong\\b", "\\bnamespace\\b", "\\boperator\\b", "\\bprivate\\b", "\\bprotected\\b", "\\bpublic\\b", "\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b", "\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b", "\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b", "\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b", "\\bvoid\\b", "\\bvolatile\\b"] self.highlightingRules = [(QRegExp(pattern), keywordFormat) for pattern in keywordPatterns] classFormat = QTextCharFormat() classFormat.setFontWeight(QFont.Bold) classFormat.setForeground(Qt.darkMagenta) self.highlightingRules.append((QRegExp("\\bQ[A-Za-z]+\\b"), classFormat)) singleLineCommentFormat = QTextCharFormat() singleLineCommentFormat.setForeground(Qt.red) self.highlightingRules.append((QRegExp("//[^\n]*"), singleLineCommentFormat)) self.multiLineCommentFormat = QTextCharFormat() self.multiLineCommentFormat.setForeground(Qt.red) quotationFormat = QTextCharFormat() quotationFormat.setForeground(Qt.darkGreen) self.highlightingRules.append((QRegExp("\".*\""), quotationFormat)) functionFormat = QTextCharFormat() functionFormat.setFontItalic(True) functionFormat.setForeground(Qt.blue) self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"), functionFormat)) self.commentStartExpression = QRegExp("/\\*") self.commentEndExpression = QRegExp("\\*/")