本文整理汇总了Python中PyQt4.Qsci.QsciAPIs.add方法的典型用法代码示例。如果您正苦于以下问题:Python QsciAPIs.add方法的具体用法?Python QsciAPIs.add怎么用?Python QsciAPIs.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.Qsci.QsciAPIs
的用法示例。
在下文中一共展示了QsciAPIs.add方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
def __init__(self, nombre_archivo, ext=''):
super(Editor, self).__init__()
self.__nombre = ""
self.texto_modificado = False
self.es_nuevo = True
self.guardado_actualmente = False
# Actualiza flags (espacios en blanco, cursor, sidebar, etc)
self.actualizar()
# Lexer
self._lexer = None
self.cargar_lexer(ext)
# Autocompletado
#FIXME:
api = QsciAPIs(self._lexer)
for palabra in keywords.keywords:
api.add(palabra)
api.prepare()
self.setAutoCompletionThreshold(1)
self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
# Indentación
self._indentacion = ESettings.get('editor/indentacionAncho')
self.send("sci_settabwidth", self._indentacion)
# Minimapa
self.minimapa = MiniMapa(self)
self.connect(self, SIGNAL("selectionChanged()"), self.minimapa.area)
self.connect(self, SIGNAL("textChanged()"),
self.minimapa.actualizar_codigo)
# Thread ocurrencias
self.hilo_ocurrencias = ThreadBusqueda()
self.connect(self.hilo_ocurrencias,
SIGNAL("ocurrenciasThread(PyQt_PyObject)"),
self.marcar_palabras)
# Analizador de estilo de código
self.checker = checker.Checker(self)
self.connect(self.checker, SIGNAL("finished()"), self._show_violations)
#self.checker.errores.connect(self._marcar_errores)
# Fuente
fuente = ESettings.get('editor/fuente')
tam_fuente = ESettings.get('editor/fuenteTam')
self.cargar_fuente(fuente, tam_fuente)
self.setMarginsBackgroundColor(QColor(self._tema['sidebar-fondo']))
self.setMarginsForegroundColor(QColor(self._tema['sidebar-fore']))
# Línea actual, cursor
self.caret_line(self._tema['caret-background'],
self._tema['caret-line'], self._tema['caret-opacidad'])
# Márgen
if ESettings.get('editor/margen'):
self.actualizar_margen()
# Brace matching
self.match_braces(Base.SloppyBraceMatch)
self.match_braces_color(self._tema['brace-background'],
self._tema['brace-foreground'])
self.unmatch_braces_color(self._tema['brace-unbackground'],
self._tema['brace-unforeground'])
示例2: RevsetEntry
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
class RevsetEntry(QsciScintilla):
returnPressed = pyqtSignal()
def __init__(self, parent=None):
super(RevsetEntry, self).__init__(parent)
self.setMarginWidth(1, 0)
self.setReadOnly(False)
self.setUtf8(True)
self.setCaretWidth(10)
self.setCaretLineBackgroundColor(QColor("#e6fff0"))
self.setCaretLineVisible(True)
self.setAutoIndent(True)
self.setMatchedBraceBackgroundColor(Qt.yellow)
self.setIndentationsUseTabs(False)
self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
self.setWrapMode(QsciScintilla.WrapWord)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
sp = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
sp.setHorizontalStretch(1)
sp.setVerticalStretch(0)
self.setSizePolicy(sp)
self.setAutoCompletionThreshold(2)
self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
self.setAutoCompletionFillupsEnabled(True)
self.setLexer(QsciLexerPython(self))
self.lexer().setFont(qtlib.getfont('fontcomment').font())
self.apis = QsciAPIs(self.lexer())
def addCompletions(self, *lists):
for list in lists:
for x, y in list:
self.apis.add(x)
self.apis.prepare()
def keyPressEvent(self, event):
if event.key() == Qt.Key_Escape:
event.ignore()
return
if event.key() in (Qt.Key_Enter, Qt.Key_Return):
if not self.isListActive():
event.ignore()
self.returnPressed.emit()
return
super(RevsetEntry, self).keyPressEvent(event)
def sizeHint(self):
return QSize(10, self.fontMetrics().height())
示例3: CSSEditor
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
class CSSEditor(BaseEditor):
def __init__(self, parent=None, line_num_margin=3, autocomplete_list=None):
super(CSSEditor, self).__init__(parent, line_num_margin, autocomplete_list)
# Set HTML lexer
self.lexer = QsciLexerCSS(self)
self.lexer.setDefaultFont(self.editor_font)
# Set auto-completion
self.api = QsciAPIs(self.lexer)
if autocomplete_list is not None:
# Add additional completion strings
for i in autocomplete_list:
self.api.add(i)
self.api.prepare()
self.setAutoCompletionThreshold(3)
self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
self.setLexer(self.lexer)
示例4: HTMLEditor
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
class HTMLEditor(BaseEditor):
def __init__(self, parent=None, line_num_margin=3, autocomplete_list=None):
super(HTMLEditor, self).__init__(parent, line_num_margin, autocomplete_list)
# Set HTML lexer
self.lexer = QsciLexerHTML(self)
self.lexer.setDefaultFont(self.editor_font)
self.lexer.setFont(self.editor_font, QsciLexerHTML.Default) # Text between tags
self.lexer.setFont(self.editor_font, QsciLexerHTML.JavaScriptWord) # Text between script tags
# Set auto-completion
self.api = QsciAPIs(self.lexer)
if autocomplete_list is not None:
# Add additional completion strings
for i in autocomplete_list:
self.api.add(i)
self.api.prepare()
self.setAutoCompletionThreshold(3)
self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
self.setAutoCompletionUseSingle(QsciScintilla.AcusExplicit)
self.setLexer(self.lexer)
示例5: initCompleter
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
def initCompleter(self):
dictionary = None
if self.db:
dictionary = self.db.connector.getSqlDictionary()
if not dictionary:
# use the generic sql dictionary
from .sql_dictionary import getSqlDictionary
dictionary = getSqlDictionary()
wordlist = []
for name, value in dictionary.iteritems():
wordlist += value # concat lists
wordlist = list(set(wordlist)) # remove duplicates
api = QsciAPIs(self.editSql.lexer())
for word in wordlist:
api.add(word)
api.prepare()
self.editSql.lexer().setAPIs(api)
示例6: PythonEditor
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
class PythonEditor(BaseEditor):
def __init__(self, parent=None, line_num_margin=3, autocomplete_list=None):
super(PythonEditor, self).__init__(parent, line_num_margin, autocomplete_list)
# Set Python lexer
self.lexer = QsciLexerPython(self)
self.lexer.setDefaultFont(self.editor_font)
self.lexer.setFont(self.editor_font, QsciLexerPython.Comment)
# Indentation warning ("The indentation is inconsistent when compared to the previous line")
self.lexer.setIndentationWarning(QsciLexerPython.Inconsistent)
# Set auto-completion
self.api = QsciAPIs(self.lexer)
if autocomplete_list is not None:
# Add additional completion strings
for i in autocomplete_list:
self.api.add(i)
self.api.prepare()
self.setAutoCompletionThreshold(3)
self.setAutoCompletionSource(QsciScintilla.AcsAll)
self.setAutoCompletionUseSingle(QsciScintilla.AcusExplicit)
self.setLexer(self.lexer)
# PEP8 tabs
self.setIndentationsUseTabs(False)
self.setAutoIndent(True)
self.setIndentationGuides(True)
# PEP8 edge column line
self.edgecol = 80
# Linters
self.linter = 'internal'
def clean_code(self):
self.setText(autopep8.fix_code(self.text(), options={'aggressive': 2}))
def check_code(self, path):
self._clear_all_margin_markers()
self.lint_data = {}
try:
warnings = linter.check(self.text(), os.path.basename(path))
for w in warnings:
w.type = 'warning'
key = w.lineno - 1
if key in self.lint_data.keys():
self.lint_data[key].append(w)
else:
self.lint_data[key] = [w]
self._add_warn_margin_marker(w.lineno - 1)
except linter.LinterSyntaxError as e:
e.type = 'error'
self.lint_data[e.lineno - 1] = e
self._add_error_margin_marker(e.lineno - 1)
except linter.LinterUnexpectedError as e:
print(e)
def margin_clicked(self, marnum, linenum, modifiers):
if self._margin_popup.isVisible():
self._hide_margin_popup()
else:
try:
warnings = self.lint_data[linenum]
desc = ''
if isinstance(warnings, linter.LinterError):
desc = warnings.message
self._show_margin_popup(desc.strip(), bg_color=self.colorErrorBackground)
else:
for warning in warnings:
desc += warning.message % warning.message_args + '\n'
self._show_margin_popup(desc.strip(), bg_color=self.colorWarnBackground)
except KeyError:
pass
return True
示例7: CommandShell
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
class CommandShell(QsciScintilla):
def __init__(self, parent=None):
super(CommandShell, self).__init__(parent)
self.setMinimumHeight(50)
self.setMaximumHeight(50)
self.settings = QSettings()
self.lex = QsciLexerPython(self)
self.apis = QsciAPIs(self.lex)
self.lex.setAPIs(self.apis)
self.setLexers()
self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
self.SendScintilla(QsciScintilla.SCI_SETVSCROLLBAR, 0)
self.setFolding(0)
self._start_prompt = _start_prompt
self.prompt = self._start_prompt
self.currentfunction = None
self.setAutoCompletionSource(self.AcsAPIs)
self.setAutoCompletionThreshold(1)
self.setAutoCompletionReplaceWord(True)
self.setCallTipsStyle(QsciScintilla.CallTipsNoContext)
self.parent().installEventFilter(self)
self.textChanged.connect(self.text_changed)
self._lastcompletions = None
def text_changed(self):
if not self.get_data().strip():
return
try:
completions = command.completions_for_line(self.get_data())
if completions == self._lastcompletions:
self.autoCompleteFromAPIs()
return
self._lastcompletions = completions
self.apis.cancelPreparation()
self.apis.clear()
for value in completions:
data = u"{}".format(value)
self.apis.add(data)
self.apis.prepare()
except command.NoFunction:
return
def end(self):
self.parent().removeEventFilter(self)
self.close()
def eventFilter(self, object, event):
if event.type() == QEvent.Resize:
self.adjust_size()
return QWidget.eventFilter(self, object, event)
def keyPressEvent(self, e):
if e.key() in (Qt.Key_Return, Qt.Key_Enter):
self.entered()
elif e.key() == Qt.Key_Escape:
self.close()
elif e.key() in (Qt.Key_Backspace, Qt.Key_Delete):
_, newindex = self.getCursorPosition()
if newindex > len(self.prompt):
QsciScintilla.keyPressEvent(self, e)
else:
QsciScintilla.keyPressEvent(self, e)
def show_prompt(self, prompt=_start_prompt, data=None):
self.clear()
if not prompt == _start_prompt:
prompt += ":"
text = prompt
if data:
text = prompt + str(data)
self.setText(text)
self.prompt = prompt
self.move_cursor_to_end()
def get_end_pos(self):
"""Return (line, index) position of the last character"""
line = self.lines() - 1
return (line, len(self.text(line)))
def move_cursor_to_end(self):
"""Move cursor to end of text"""
line, index = self.get_end_pos()
self.setCursorPosition(line, index)
self.ensureCursorVisible()
self.ensureLineVisible(line)
def get_data(self):
line = self.text()
line = line[len(self.prompt):]
return line
def entered(self):
line = self.get_data()
#.........这里部分代码省略.........
示例8: MultipleCppEditor
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
class MultipleCppEditor(QtGui.QTabWidget):
'''
classdocs
'''
def __init__(self, parent=None):
'''
Constructor
'''
super(MultipleCppEditor, self).__init__(parent)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.prepareLibraryAPIs()
self.findDlg = FindDialog(self)
self.setAcceptDrops(True)
#self.setTabShape(QtGui.QTabWidget.Triangular)
self.setMovable(True)
self.setTabsClosable(True)
self.connect(self, QtCore.SIGNAL('tabCloseRequested(int)'), self.closeFile)
self.sampleProjects = []
try:
for group in getExampleProjects(scanFirmwareLibs()):
for fname in group[1]:
self.sampleProjects.append(fname)
# print self.sampleProjects
except:
pass
if self.count()==0:
self.newFile()
def newFile(self):
child = CppEditor(self, None, self.sampleProjects)
self.addTab(child, PROJECT_NONAME + " * ")
self.setCurrentIndex(self.count()-1)
self.setTabToolTip(self.currentIndex(), child.currentFile())
def openFile(self, fileName=None):
if fileName == None: # prompt open dialog if filename is not specified
fileName = QtGui.QFileDialog.getOpenFileName(
self, self.tr("Open Source File"),
"", PROJECT_ALIAS + " (*" + PROJECT_EXT + ");;"
"C Source File (*.c);;Text File (*.txt);;All files (*.*)" )
if fileName == "":
return False
#check if it's already opened
for i in range(self.count()):
child = self.widget(i)
if fileName == child.currentFile(): # file already opened
self.setCurrentIndex(i)
return True
child = CppEditor(self, fileName, self.sampleProjects)
tabtext = os.path.basename( str(fileName) )
if tabtext.lower().find(PROJECT_EXT) == len(tabtext) - len(PROJECT_EXT):
tabtext = tabtext[:tabtext.lower().find(PROJECT_EXT)]
self.addTab(child, tabtext)
self.setCurrentIndex(self.count()-1)
self.setTabToolTip(self.currentIndex(), child.currentFile())
return True
def saveFile(self):
child = self.currentWidget()
if child == None:
return None
rc = child.save()
if rc:
fileName = child.currentFile()
tabtext = os.path.basename( str(fileName) )
if tabtext.lower().find(PROJECT_EXT) == len(tabtext) - len(PROJECT_EXT):
tabtext = tabtext[:tabtext.lower().find(PROJECT_EXT)]
self.setTabText(self.currentIndex(), tabtext)
self.setTabToolTip(self.currentIndex(), fileName)
return True
return False
def saveFileAs(self):
child = self.currentWidget()
rc = child.saveAs()
if rc:
fileName = child.currentFile()
tabtext = os.path.basename( str(fileName) )
if tabtext.lower().find(PROJECT_EXT) == len(tabtext) - len(PROJECT_EXT):
tabtext = tabtext[:tabtext.lower().find(PROJECT_EXT)]
self.setTabText(self.currentIndex(), tabtext)
self.setTabToolTip(self.currentIndex(), fileName)
return True
return False
def closeFile(self, idx = 0):
if self.count()==0:
return True# nothing to close
# check if the file has changed before closing
child = self.widget(idx)
if child.isModified:
result = QtGui.QMessageBox.question(self, "Modified",
'Save changes on "' + child.currentFile() + '" ?',
#.........这里部分代码省略.........
示例9: CppEditor
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
#.........这里部分代码省略.........
qfile.close()
return ret
def saveFile(self, fileName):
if str(fileName).find(' ')>=0:
QtGui.QMessageBox.warning(self, PROJECT_ALIAS,
'File path "%s" contains space(s). Please save to a valid location.'%fileName)
return None
qfile = QtCore.QFile(fileName)
if not qfile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
QtGui.QMessageBox.warning(self, PROJECT_ALIAS,
"Cannot write file %s:\n%s." % (fileName, qfile.errorString()))
return None
try:
qfile.writeData(self.text())
except:
QtGui.QMessageBox.warning(self, PROJECT_ALIAS,
"Failed to save %s." % fileName )
qfile.close()
return None
qfile.close()
self.curFile = fileName
self.isUntitled = False
self.isModified = False
return fileName
def saveAs(self):
fileName = QtGui.QFileDialog.getSaveFileName(self, "Save As",
self.curFile, PROJECT_ALIAS + " (*" + USER_CODE_EXT + ");;" +
"C source (*.c);;C++ source (*.cpp);;Text File (*.txt);;All files (*.*)" )
if not fileName:
return None
return self.saveFile(fileName)
def save(self):
f1 = os.path.abspath(self.curFile)
for fname in self.roFiles:
if f1 == os.path.abspath(fname): # same file
if QtGui.QMessageBox.question(self.parent, "Project is read-only",
"This project is marked as \"read-only\".\n" + \
"Please click \"Cancel\" and save this to another location.\n\n" + \
"Continue saving the current project anyway?", "OK", "Cancel"):
return None
#return self.saveAs()
return self.saveFile(self.curFile)
if self.isUntitled:
return self.saveAs()
else:
return self.saveFile(self.curFile)
def currentFile(self):
return self.curFile
def modified(self):
return self.isModified
def updateApiKeywords(self):
self.libraryAPIs.clear()
self.apiKeywords = self.parent.getDefaultKeywords()
headerfiles = []
for line in range(self.lines()):
txt = str(self.text(line)).strip()
if txt.find('int') == 0: # e.g. reached "int main()"
break
elif txt.find('#include') == 0:
txt = ''.join(txt.split())
temp = txt[len('#includes')-1 : ]
header = temp[1:-1] # get the header file
hfile = os.path.join('libraries', header[:-2], header)
if os.path.isfile(hfile):
if not (hfile in headerfiles): headerfiles.append( hfile )
if len( headerfiles ):
#print 'parsing: ', headerfiles
self.apiKeywords += getLibraryKeywords( headerfiles )
#self.apiKeywords = list(set(self.apiKeywords)) # remove duplicates
for keyword in self.apiKeywords:
self.libraryAPIs.add( keyword )
self.libraryAPIs.prepare()
self.lexer.setAPIs(self.libraryAPIs)
def insertIncludeDirective(self, library=''):
directive = '#include <' + library + '.h>\r\n'
insert_pos = 0
found_inc = False
for line in range(self.lines()):
txt = str(self.text(line)).strip()
if txt.find('int') == 0: # e.g. reached "int main()"
insert_pos = line - 1
break
elif txt.find('#include') == 0:
found_inc = True
elif found_inc:
insert_pos = line
break
if insert_pos < 0 or insert_pos >= self.lines():
insert_pos = 0
self.insertAt(directive, insert_pos, 0)
self.updateApiKeywords()
示例10: Editor
# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import add [as 别名]
#.........这里部分代码省略.........
# Analizador de estilo de código
self.checker = None
if settings.get_setting('editor/style-checker'):
self.load_checker()
# Fuente
font = settings.get_setting('editor/font')
font_size = settings.get_setting('editor/size-font')
self.load_font(font, font_size)
self.setMarginsBackgroundColor(QColor(self.scheme['SidebarBack']))
self.setMarginsForegroundColor(QColor(self.scheme['SidebarFore']))
# Línea actual
self.send("sci_setcaretlinevisible",
settings.get_setting('editor/show-caret-line'))
self.send("sci_setcaretlineback", QColor(self.scheme['CaretLineBack']))
self.send("sci_setcaretfore", QColor(self.scheme['CaretLineFore']))
self.send("sci_setcaretlinebackalpha", self.scheme['CaretLineAlpha'])
# Cursor
caret_period = settings.get_setting('editor/cursor-period')
self.send("sci_setcaretperiod", caret_period)
# Márgen
if settings.get_setting('editor/show-margin'):
self.update_margin()
# Brace matching
self.setBraceMatching(int(settings.get_setting('editor/match-brace')))
self.setMatchedBraceBackgroundColor(QColor(
self.scheme['MatchedBraceBack']))
self.setMatchedBraceForegroundColor(QColor(
self.scheme['MatchedBraceFore']))
self.setUnmatchedBraceBackgroundColor(QColor(
self.scheme['UnmatchedBraceBack']))
self.setUnmatchedBraceForegroundColor(QColor(
self.scheme['UnmatchedBraceFore']))
# Selecciones Múltiples
self.send("sci_setadditionalcaretfore", QColor(157, 64, 40))
self.send("sci_setadditionalcaretsblink", 1)
self.send("sci_setadditionalselalpha", 100)
self.send("sci_setmultipleselection", 1)
self.send("sci_setadditionalselectiontyping", 1)
# Conexiones
self.connect(self, SIGNAL("linesChanged()"), self.update_sidebar)
self.connect(self, SIGNAL("textChanged()"), self._add_marker_modified)
@property
def filename(self):
return self.obj_file.filename
@property
def is_modified(self):
return self.isModified()
def load_font(self, fuente, tam):
self._font = QFont(fuente, tam)
if self._lexer is None:
self.setFont(self._font)
else:
self._lexer.setFont(self._font)
self.setMarginsFont(self._font)
def load_checker(self, activated=True):
if activated and self.checker is not None:
return
if not activated:
self.checker = None
self.clear_indicators(Editor.WARNING_INDICATOR)
else:
self.checker = checker.Checker(self)