def findInField(self, lookFor, parameters): cursor = self.fldbk.dData.textCursor() format = QtGui.QTextCharFormat() format.setBackground(QtGui.QBrush(QtGui.QColor("yellow"))) if parameters[0] == 1: lookFor = self.removeAccents(lookFor) if parameters[1] == 1: lookFor = self.removeDiacrits(lookFor) if "#" in lookFor: lookFor = self.setEdge(lookFor) if parameters[2] == 0: regex = QtCore.QRegularExpression( lookFor, QtCore.QRegularExpression.CaseInsensitiveOption) else: regex = QtCore.QRegularExpression(lookFor) pos = 0 index = QtCore.QRegularExpressionMatch() dataset = self.fldbk.dData.toPlainText() index = regex.match(dataset, pos) while (index.hasMatch()): cursor.setPosition(index.capturedStart()) cursor.movePosition(QtGui.QTextCursor.StartOfBlock) cursor.movePosition(QtGui.QTextCursor.EndOfBlock, QtGui.QTextCursor.KeepAnchor) cursor.mergeCharFormat(format) pos = index.capturedStart() + len(index.captured()) index = regex.match(dataset, pos)
def highlightBlock(self, text): cl_known = QtGui.QColor(0x000000) cl_unknown = QtGui.QColor(0xFF0000) cl_tag = QtGui.QColor(0x000088) cl_cmd = QtGui.QColor(0x2200FF) cl_wkblue = QtGui.QColor(0x000077) known = QtGui.QTextCharFormat() unknown = QtGui.QTextCharFormat() tag = QtGui.QTextCharFormat() cmd = QtGui.QTextCharFormat() hitting = QtGui.QTextCharFormat() known.setForeground(cl_known) unknown.setForeground(cl_unknown) tag.setForeground(cl_tag) cmd.setForeground(cl_cmd) hitting.setForeground(cl_wkblue) cmd.setFontWeight(QtGui.QFont.Bold) word = QtCore.QRegularExpression("[^<>\\[\\]=\\(\\).,;\\s\\n]+") tags = QtCore.QRegularExpression("[<>\\[\\]]") links = QtCore.QRegularExpression("=.+?>") i = word.globalMatch(text) while i.hasNext(): match = i.next() end = match.capturedStart() + match.capturedLength() w = text[match.capturedStart():end] if w in self.known_words: self.setFormat(match.capturedStart(), match.capturedLength(), known) elif w in commands: self.setFormat(match.capturedStart(), match.capturedLength(), cmd) elif w in self.keywords: self.setFormat(match.capturedStart(), match.capturedLength(), tag) elif w in self.incomplete_keywords: self.setFormat(match.capturedStart(), match.capturedLength(), hitting) else: self.setFormat(match.capturedStart(), match.capturedLength(), unknown) i = tags.globalMatch(text) while i.hasNext(): match = i.next() self.setFormat(match.capturedStart(), match.capturedLength(), tag) i = links.globalMatch(text) while i.hasNext(): match = i.next() self.setFormat(match.capturedStart() + 1, match.capturedLength() - 2, cmd)
def highlight_python(self): for i in self.py_keywords + self.py_builtins + self.py_constants: self.highlight_rules.append( (QtCore.QRegularExpression('\\b' + i + '\\b'), self.keyword_format)) comment_format = QtGui.QTextCharFormat(self.base_format) comment_format.setForeground(QtCore.Qt.darkGreen) self.highlight_rules.append( (QtCore.QRegularExpression('#.*'), comment_format))
def __init__(self, document): QtGui.QSyntaxHighlighter.__init__(self, document) rules = [] rules += [(r'\b%s\b' % w, 0, STYLES['domainword']) for w in ContextTraceHighlighter.domainwords] rules += [(r'\b%s\b' % w, 0, STYLES['domainvalue']) for w in ContextTraceHighlighter.domainvalues] rules += [(r'\b%s\b' % w, 0, STYLES['redword']) for w in ContextTraceHighlighter.redwords] rules += [(r'\b%s\b' % w, 0, STYLES['nullword']) for w in ContextTraceHighlighter.nullwords] rules += [(r'%s' % b, 0, STYLES['brace']) for b in ContextTraceHighlighter.braces] rules += [ (r'\bNP_ID\b:([A-Za-z0-9]+)', 1, STYLES['np']), (r'\"notificationPointId\":([A-Za-z0-9]+)', 1, STYLES['np']), (r'\bDP_ID\b:([A-Za-z0-9]+)', 1, STYLES['dp']), (r'\"destinationId\":([A-Za-z0-9]+)', 1, STYLES['dp']), (r'\bCONT_ID\b:([A-Za-z0-9]+)', 1, STYLES['trayid']), (r'\"trayId\":([A-Za-z0-9]+)', 1, STYLES['trayid']), (r'\bGLOBAL_ID\b:([A-Za-z0-9]+)', 1, STYLES['globalid']), (r'\"globalId\":([A-Za-z0-9]+)', 1, STYLES['globalid']), (r'\bLPN\b:([A-Za-z0-9]+)', 1, STYLES['lpn']), (r'\"transportGoodsId[0-9]?\":([A-Za-z0-9"]+)', 1, STYLES['lpn']), (r'\bTimeState\b:([A-Za-z0-9_]+)', 1, STYLES['domainvalue']), (r'\bBagTagStateDerived\b:([A-Za-z0-9_]+)', 1, STYLES['domainvalue']), (r'\btransportState\b:([A-Za-z0-9_]+)', 1, STYLES['domainvalue']), (r'\bOperationalState\b:([A-Za-z0-9_]+)', 1, STYLES['domainvalue']), (r'\bStep\b.[A-Z_]*\-?[0-9.]+', 0, STYLES['tcstep']) ] self.rules = [(QtCore.QRegularExpression(pat, QtCore.QRegularExpression.CaseInsensitiveOption), index, fmt) for (pat, index, fmt) in rules]
def findMenu(fldbk): target = QtWidgets.QInputDialog().getText(fldbk, "Find", "Enter text to find.") if target[1] == True and len(target[0]) != 0: regExp = QtCore.QRegularExpression( target[0], QtCore.QRegularExpression.CaseInsensitiveOption) hits = searchXML(fldbk, regExp) if hits: dataIndex.searchResults = hits dataIndex.searchPointer = 1
def findpattern(self): regex_pattern = self.expression_box.text() regex = qtc.QRegularExpression(regex_pattern) i = qtc.QRegularExpressionMatchIterator( regex.globalMatch(self.textedit.toPlainText())) word = [] self.statusBar().showMessage('Finding.....') while i.hasNext(): match = qtc.QRegularExpressionMatch(i.next()) word.append(match.captured(0)) self.dialogbox = DialogBox(word) self.dialogbox.exec()
def searchElement(self, entry, term, target): '''tests the entry to see if the search term is in the target string''' '''parameters = [accent,diacrit,case,append,recOnly,wholeWord]''' if target == None or target == False: hit = False return hit lookFor = term[1].strip() if '@' in term[0]: if lookFor[-1] == ".": lookFor = lookFor.replace('.', '') polarity = None if lookFor[0] == '¬': lookFor = lookFor[1:] polarity = 'neg' '''perform a search that abstracts over accents''' #parameters[0] flags accents if self.parameters[1] == 1: '''perform a search that abstracts over diacritics''' #parameters[1] flags diacrits lookFor = self.removeDiacrits(lookFor) if self.parameters[0] == 1: lookFor = self.removeAccents(lookFor) if self.parameters[5] == 1: #if whole word search lookFor = '(\s|^)' + lookFor + '(\s|$)' elif "#" in lookFor: lookFor = self.setEdge(lookFor) if self.parameters[2] == 0: #parameters[2] flags caps p = QtCore.QRegularExpression( lookFor, QtCore.QRegularExpression.CaseInsensitiveOption) else: p = QtCore.QRegularExpression( lookFor, QtCore.QRegularExpression.CaseInsensitiveOption) m = QtCore.QRegularExpressionMatch() m = p.match(target) if m.hasMatch(): if polarity == 'neg': hit = False else: hit = True else: hit = False return hit
def createEditor(self, obj: model.CustomCSoundPort, delegate: QtWidgets.QAbstractItemDelegate, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex) -> QtWidgets.QWidget: editor = super().createEditor(obj, delegate, parent, option, index) assert isinstance(editor, QtWidgets.QLineEdit) editor.setValidator( QtGui.QRegularExpressionValidator( QtCore.QRegularExpression(r'[a-zA-Z][-_:a-zA-Z0-9]{0,32}'))) return editor
def Sanitize_SQL( raw_string ): # Got regex from https://stackoverflow.com/questions/9651582/sanitize-table-column-name-in-dynamic-sql-in-net-prevent-sql-injection-attack if( ';' in raw_string ): return "" re = QtCore.QRegularExpression( '''^[\p{L}{\p{Nd}}$#_][\p{L}{\p{Nd}}@$#_]*$''' ); match = re.match( raw_string ); hasMatch = match.hasMatch(); if( hasMatch ): return raw_string else: return ""
def fuzzyFind(fldbk): target = QtWidgets.QInputDialog().getText( fldbk, "Fuzzy find", "Enter text to find. Accents, caps,\n" "and diacrits will be ignored.") if target[1] == True and len(target[0]) != 0: lookFor = target[0] lookFor = SearchEngine.removeDiacrits(SearchEngine, lookFor) lookFor = SearchEngine.removeAccents(SearchEngine, lookFor) regExp = QtCore.QRegularExpression( lookFor, QtCore.QRegularExpression.CaseInsensitiveOption) hits = searchXML(fldbk, regExp) if hits: dataIndex.fuzzyResults = hits dataIndex.fuzzyPointer = 1
def keyPressEvent(self, keyEvent): k = keyEvent.key() if k == Qt.Key_Return: self.parent.accept() elif k in (Qt.Key_Up, Qt.Key_Down): self.parent.view.keyPressEvent(keyEvent) elif k == Qt.Key_Escape: self.parent.dismiss() else: # re = QRegularExpression(pattern, QRegularExpression.CaseInsensitiveOption | QRegularExpression.DotMatchesEverythingOption) rx = QtCore.QRegularExpression( self.text(), QtCore.QRegularExpression.CaseInsensitiveOption | QtCore.QRegularExpression.DotMatchesEverythingOption) self.parent.proxy_model.setFilterRegularExpression(rx) self.parent.proxy_model.setFilterWildcard("*" + self.text() + "*") super().keyPressEvent(keyEvent)
def createEditor(self, obj: model.CustomCSoundPort, delegate: QtWidgets.QAbstractItemDelegate, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex) -> QtWidgets.QWidget: editor = super().createEditor(obj, delegate, parent, option, index) assert isinstance(editor, QtWidgets.QLineEdit) if obj.type == node_db.PortDescription.EVENTS: regex = r'[0-9]+' else: regex = obj.csound_name_prefix() + r'[a-zA-Z0-9_]{1,30}' editor.setValidator( QtGui.QRegularExpressionValidator( QtCore.QRegularExpression(regex))) return editor
def dropEvent(self, event): if event.mimeData().hasFormat(fridgetMagnetsMimeType()): mime = event.mimeData() itemData = mime.data(fridgetMagnetsMimeType()) dataStream = QtCore.QDataStream(itemData, QtCore.QIODevice.ReadOnly) text = "" offset = QtCore.QPoint() text = dataStream.readQString() dataStream >> offset newLabel = DragLabel(text, self) newLabel.move(event.pos() - offset) newLabel.show() newLabel.setAttribute(QtCore.Qt.WA_DeleteOnClose) if event.source() is self: event.setDropAction(QtCore.Qt.MoveAction) event.accept() else: event.acceptProposedAction() elif event.mimeData().hasText(): text = event.mimeData().text() re = QtCore.QRegularExpression(r"\\s+") pieces = [] iterator = re.globalMatch(text) start, end = 0, 0 while iterator.hasNext(): match = iterator.next() end = match.capturedStart() pieces.append(text[start:end - start]) start = match.capturedEnd() pieces.append(text[start:end - start]) position = event.pos() for piece in pieces: newLabel = DragLabel(piece, self) newLabel.move(position) newLabel.show() newLabel.setAttribute(QtCore.Qt.WA_DeleteOnClose) position += QtCore.QPoint(newLabel.width(), 0) event.acceptProposedAction() else: event.ignore()
def Read_From_Socket( self, peer_identifier ): #print( "Message at: " + QtCore.QDateTime.currentDateTime().toString() ) connected_device = self.active_connections[ peer_identifier ] connected_device.timer.setInterval( self.timeout_ms ) data = connected_device.pSocket.readAll() connected_device.raw_data_stream += bytes(data) #connected_device.raw_data_stream = split_by_line[-1] pure_text_messages = [] # This chunk will extract any files being written over the socket re = QtCore.QRegularExpression( '''^FILE\s*"([^\\<>:;,?"*|/]+)"\s*(\d+)$''' ); rerun = True while rerun: rerun = False split_by_line = connected_device.raw_data_stream.split( b'\n' ) connected_device.raw_data_stream = split_by_line[-1] # Put back only the unfinished line for index,line in enumerate( split_by_line[:-1] ): try: if line == b"Ping": continue else: match = re.match( line.decode() ); except Exception: continue if not match.hasMatch(): pure_text_messages.append( line ) continue file_name = match.captured( 1 ) size_of_file = int(match.captured( 2 )) size_of_header = len(line) + 1 connected_device.raw_data_stream = b'\n'.join( split_by_line[index:] ) if( len(connected_device.raw_data_stream) >= size_of_header + size_of_file ): self.File_Recieved.emit( file_name, connected_device.raw_data_stream[size_of_header:size_of_header + size_of_file], connected_device ) connected_device.raw_data_stream = connected_device.raw_data_stream[size_of_header + size_of_file:] rerun = True # Make sure there were no other interesting messages break for one_line in pure_text_messages: self.Reply_Recieved.emit( one_line.decode(), connected_device )
def __init__(self, creds: Mapping, *args, **kwargs): super(LoginDialog, self).__init__(*args, **kwargs) self.creds = creds self.setupUi(self) #diable sign-in by default self.loginButton.setEnabled(False) #validation, adapted from https://www.walletfox.com/course/qlineeditemailvalidation.php expression = QtCore.QRegularExpression( "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b", QtCore.QRegularExpression.CaseInsensitiveOption) self.emailInput.setValidator( QtGui.QRegularExpressionValidator(expression, self)) #connect validation self.emailInput.textChanged.connect(self.__validate) self.passwordInput.textChanged.connect(self.__validate) self.loginButton.clicked.connect(self.__login) self.cancelButton.clicked.connect(self.__cancel)
def __init__(self, *args, **kwargs): """ Defines the Basic rules as well as color schemes. """ super().__init__(*args, **kwargs) rules = [] # rules rules += [(r'{}\b'.format(s), 'statement') for s in LarkHighlighter.statements] rules += [ # from '#' until a newline (r'\/\/[^\n]*', 'comment'), # Double-quoted string, possibly containing escape sequences (r'"[^"\\]*(\\.[^"\\]*)*"', 'string'), ] self.rules = [(QtCore.QRegularExpression(pattern), LarkHighlighter.styles[format]) for (pattern, format) in rules]
def __init__(self, parent=None): super().__init__(parent) self.keywordFormat = QtGui.QTextCharFormat() self.keywordFormat.setForeground(Qt.darkBlue) self.keywordFormat.setFontWeight(QtGui.QFont.Bold) self.highlightingRules = [] for pattern in keywordPatterns: self.highlightingRules.append( (QtCore.QRegularExpression(pattern), self.keywordFormat)) self.classFormat = QtGui.QTextCharFormat() self.classFormat.setFontWeight(QtGui.QFont.Bold) self.classFormat.setForeground(Qt.darkMagenta) self.highlightingRules.append( (QtCore.QRegularExpression(r'\bQ[A-Za-z]+\b'), self.classFormat)) self.quotationFormat = QtGui.QTextCharFormat() self.quotationFormat.setForeground(Qt.darkGreen) self.highlightingRules.append( (QtCore.QRegularExpression('".*"'), self.quotationFormat)) self.functionFormat = QtGui.QTextCharFormat() self.functionFormat.setFontItalic(True) self.functionFormat.setForeground(Qt.blue) self.highlightingRules.append( (QtCore.QRegularExpression(r'\b[A-Za-z0-9_]+(?=\()'), self.functionFormat)) self.singleLineCommentFormat = QtGui.QTextCharFormat() self.singleLineCommentFormat.setForeground(Qt.red) self.highlightingRules.append((QtCore.QRegularExpression('//[^\n]*'), self.singleLineCommentFormat)) self.multiLineCommentFormat = QtGui.QTextCharFormat() self.multiLineCommentFormat.setForeground(Qt.red) self.commentStartExpression = QtCore.QRegExp(r'/\*') self.commentEndExpression = QtCore.QRegularExpression(r'\*/')
def highlight_cpp(self): for i in self.cpp_keywords: self.highlight_rules.append( (QtCore.QRegularExpression('\\b' + i + '\\b'), self.keyword_format)) class_format = QtGui.QTextCharFormat(self.base_format) class_format.setFontWeight(QtGui.QFont.Bold) class_format.setForeground(QtCore.Qt.darkMagenta) self.highlight_rules.append( (QtCore.QRegularExpression('\\bQ[A-Za-z]+\\b'), class_format)) quotation_format = QtGui.QTextCharFormat(self.base_format) quotation_format.setForeground(QtCore.Qt.darkGreen) self.highlight_rules.append( (QtCore.QRegularExpression('\".*\"'), quotation_format)) function_format = QtGui.QTextCharFormat(self.base_format) function_format.setFontItalic(True) function_format.setForeground(QtCore.Qt.blue) self.highlight_rules.append( (QtCore.QRegularExpression('\\b[A-Za-z0-9_]+(?=\\()'), function_format)) single_line_comment_format = QtGui.QTextCharFormat(self.base_format) single_line_comment_format.setForeground(QtCore.Qt.gray) self.highlight_rules.append((QtCore.QRegularExpression('//[^\n]*'), single_line_comment_format)) single_line_comment_format1 = QtGui.QTextCharFormat(self.base_format) single_line_comment_format1.setForeground(QtCore.Qt.darkGreen) self.highlight_rules.append( (QtCore.QRegularExpression('<.*>'), single_line_comment_format1)) multi_line_comment_format = QtGui.QTextCharFormat(self.base_format) multi_line_comment_format.setForeground(QtCore.Qt.red)
def get_locked_header(self): reverse_header = {v: k for k, v in self.model.header.items()} return [reverse_header[head] for head in self.model.locked_columns] def filter(self, head, filter, regex=False, case=False, widget=None): try: if head is None: self.proxy.setFilterKeyColumn(-1) else: self.proxy.setFilterKeyColumn(self.get_header(head)) except KeyError: pass else: if regex: filter = QtCore.QRegularExpression(filter) if filter.isValid(): if widget: widget.setStyleSheet('') if case: filter.setPatternOptions( QtCore.QRegularExpression.UseUnicodePropertiesOption | QtCore.QRegularExpression.DotMatchesEverythingOption ) else: filter.setPatternOptions( QtCore.QRegularExpression.CaseInsensitiveOption | QtCore.QRegularExpression.UseUnicodePropertiesOption | QtCore.QRegularExpression.DotMatchesEverythingOption ) self.proxy.setFilterRegularExpression(filter)
def __init__(self, parent=None): super().__init__(parent) self.hsFilterString = QtCore.QRegularExpression(r".*")
return QModelIndex() def data(self, index, role): return self.sourceModel().data(self.mapToSource(index), role) def item(self, row, column) -> QtGui.QStandardItem: return self.sourceModel().item(column, row) def headerData(self, section, orientation, role): return self.sourceModel().headerData(section, orientation, role) if __name__ == '__main__': testStrings = ['Site 1', 'Site 10', 'Site 100', 'Site 2', 'Site 22'] siteFilterString = QtCore.QRegularExpression(r"\b[A-Za-z]+\s(0|1|2)\b") result = [] for s in testStrings: result.append(siteFilterString.match(s).hasMatch()) print(result) siteFilterString.setPattern("") result = [] for s in testStrings: result.append(siteFilterString.match(s).hasMatch()) print(result) siteFilterString.setPattern("$-") result = [] for s in testStrings: result.append(siteFilterString.match(s).hasMatch())
def showpattern(self): regex_pattern = self.expression_box.text() regex = qtc.QRegularExpression(regex_pattern) if regex_pattern: flag = qtg.QTextDocument.FindCaseSensitively self.textedit.find(regex, flag)