当前位置: 首页>>代码示例>>Python>>正文


Python QsciAPIs.prepare方法代码示例

本文整理汇总了Python中PyQt4.Qsci.QsciAPIs.prepare方法的典型用法代码示例。如果您正苦于以下问题:Python QsciAPIs.prepare方法的具体用法?Python QsciAPIs.prepare怎么用?Python QsciAPIs.prepare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt4.Qsci.QsciAPIs的用法示例。


在下文中一共展示了QsciAPIs.prepare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: PrepareAPIDialog

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [as 别名]
class PrepareAPIDialog(QDialog):
    def __init__(self, api_lexer, api_files, pap_file, parent=None):
        QDialog.__init__(self, parent)
        self.ui = Ui_APIsDialogPythonConsole()
        self.ui.setupUi(self)
        self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Compile APIs"))
        self.ui.plainTextEdit.setVisible(False)
        self.ui.textEdit_Qsci.setVisible(False)
        self.adjustSize()
        self._api = None
        self.ui.buttonBox.rejected.connect(self._stopPreparation)
        self._api_files = api_files
        self._api_lexer = api_lexer
        self._pap_file = pap_file

    def _clearLexer(self):
        # self.ui.textEdit_Qsci.setLexer(0)
        self.qlexer = None

    def _stopPreparation(self):
        if self._api is not None:
            self._api.cancelPreparation()
        self._api = None
        self._clearLexer()
        self.close()

    def _preparationFinished(self):
        self._clearLexer()
        if os.path.exists(self._pap_file):
            os.remove(self._pap_file)
        self.ui.label.setText(QCoreApplication.translate("PythonConsole", "Saving prepared file..."))
        prepd = self._api.savePrepared(unicode(self._pap_file))
        rslt = self.trUtf8("Error")
        if prepd:
            rslt = QCoreApplication.translate("PythonConsole", "Saved")
        self.ui.label.setText(u"{0} {1}".format(self.ui.label.text(), rslt))
        self._api = None
        self.ui.progressBar.setVisible(False)
        self.ui.buttonBox.button(QDialogButtonBox.Cancel).setText(QCoreApplication.translate("PythonConsole", "Done"))
        self.adjustSize()

    def prepareAPI(self):
        # self.ui.textEdit_Qsci.setLexer(0)
        exec(u"self.qlexer = {0}(self.ui.textEdit_Qsci)".format(self._api_lexer))
        # self.ui.textEdit_Qsci.setLexer(self.qlexer)
        self._api = QsciAPIs(self.qlexer)
        self._api.apiPreparationFinished.connect(self._preparationFinished)
        for api_file in self._api_files:
            self._api.load(unicode(api_file))
        try:
            self._api.prepare()
        except Exception as err:
            self._api = None
            self._clearLexer()
            self.ui.label.setText(QCoreApplication.translate("PythonConsole", "Error preparing file..."))
            self.ui.progressBar.setVisible(False)
            self.ui.plainTextEdit.setVisible(True)
            self.ui.plainTextEdit.insertPlainText(err)
            self.ui.buttonBox.button(QDialogButtonBox.Cancel).setText(self.trUtf8("Done"))
            self.adjustSize()
开发者ID:Geoneer,项目名称:QGIS,代码行数:62,代码来源:console_compile_apis.py

示例2: __init__

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [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'])
开发者ID:ekimdev,项目名称:edis,代码行数:58,代码来源:editor.py

示例3: RevsetEntry

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [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())
开发者ID:velorientc,项目名称:git_test7,代码行数:54,代码来源:revset.py

示例4: CSSEditor

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [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)
开发者ID:nmichaud,项目名称:fiddle,代码行数:19,代码来源:Editors.py

示例5: HTMLEditor

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [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)
开发者ID:akehrer,项目名称:fiddle,代码行数:22,代码来源:Editors.py

示例6: initCompleter

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [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)
开发者ID:herow,项目名称:planning_qgis,代码行数:22,代码来源:dlg_sql_window.py

示例7: __init__

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [as 别名]
    def __init__(self, parent=None):
        QsciScintilla.__init__(self, parent)
        self.setTabWidth(4)
        self.setTabIndents(True)
        self.setIndentationsUseTabs(False)

        self._lexer = QsciLexerPython()
        self._lexer.setFont(QFont('DejaVu Sans Mono'))
        self._lexer.setIndentationWarning(QsciLexerPython.Tabs)

        # load current preview to lexer
        api = QsciAPIs(self._lexer)
        api.load('/tmp/preview.py')
        api.prepare()

        self.setLexer(self._lexer)
        self.setAutoCompletionSource(QsciScintilla.AcsAll)
        self.setAutoCompletionThreshold(2)
        self.setAutoIndent(True)
        self.setCaretForegroundColor(g.cursor_color)
        self.zoomTo(5)
开发者ID:sem23,项目名称:roslab_ide,代码行数:23,代码来源:PyEditor.py

示例8: PrepareAPIs

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [as 别名]
class PrepareAPIs(QObject):

    def __init__(self, api_lexer, api_files, pap_file):
        QObject.__init__(self)
        self._api = None
        self._api_files = api_files
        self._api_lexer = api_lexer
        self._pap_file = pap_file

    def _clearLexer(self):
        self.qlexer = None

    def _stopPreparation(self):
        if self._api is not None:
            self._api.cancelPreparation()
        self._api = None
        sys.exit(1)

    def _preparationFinished(self):
        self._clearLexer()
        try:
            if os.path.exists(self._pap_file):
                os.remove(self._pap_file)
            prepd = self._api.savePrepared(unicode(self._pap_file))
            self._api = None
            sys.exit(0 if prepd else 1)
        except Exception as err:
            self._api = None
            sys.exit(1)

    def prepareAPI(self):
        try:
            self._api = QsciAPIs(self._api_lexer)
            self._api.apiPreparationFinished.connect(self._preparationFinished)
            for api_file in self._api_files:
                self._api.load(unicode(api_file))
            self._api.prepare()
        except Exception as err:
            self._api = None
            sys.exit(1)
开发者ID:Geoneer,项目名称:QGIS,代码行数:42,代码来源:generate_console_pap.py

示例9: Editor

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [as 别名]

#.........这里部分代码省略.........

        self.lexer = QsciLexerPython()
        self.lexer.setIndentationWarning(QsciLexerPython.Inconsistent)
        self.lexer.setFoldComments(True)
        self.lexer.setFoldQuotes(True)

        loadFont = self.settings.value("pythonConsole/fontfamilytextEditor", "Monospace").toString()
        fontSize = self.settings.value("pythonConsole/fontsizeEditor", 10).toInt()[0]

        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setColor(Qt.red, 1)
        self.lexer.setColor(Qt.darkGreen, 5)
        self.lexer.setColor(Qt.darkBlue, 15)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        self.api = QsciAPIs(self.lexer)
        chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True).toBool()
        if chekBoxAPI:
            self.api.loadPrepared( QgsApplication.pkgDataPath() + "/python/qsci_apis/pyqgis_master.pap" )
        else:
            apiPath = self.settings.value("pythonConsole/userAPI").toStringList()
            for i in range(0, len(apiPath)):
                self.api.load(QString(unicode(apiPath[i])))
            self.api.prepare()
            self.lexer.setAPIs(self.api)

        self.setLexer(self.lexer)

    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_end_pos(self):
        """Return (line, index) position of the last character"""
        line = self.lines() - 1
        return (line, self.text(line).length())

    def contextMenuEvent(self, e):
        menu = QMenu(self)
        iconRun = QgsApplication.getThemeIcon("console/iconRunConsole.png")
        iconCodePad = QgsApplication.getThemeIcon("console/iconCodepadConsole.png")
        iconNewEditor = QgsApplication.getThemeIcon("console/iconTabEditorConsole.png")
        iconCommentEditor = QgsApplication.getThemeIcon("console/iconCommentEditorConsole.png")
        iconUncommentEditor = QgsApplication.getThemeIcon("console/iconUncommentEditorConsole.png")
        iconSettings = QgsApplication.getThemeIcon("console/iconSettingsConsole.png")
        hideEditorAction = menu.addAction("Hide Editor",
                                     self.hideEditor)
        menu.addSeparator()
        newTabAction = menu.addAction(iconNewEditor,
                                    "New Tab",
                                    self.parent.newTab, 'Ctrl+T')
        closeTabAction = menu.addAction("Close Tab",
                                    self.parent.close, 'Ctrl+W')
开发者ID:vinayan,项目名称:Quantum-GIS,代码行数:70,代码来源:console_editor.py

示例10: APIs

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [as 别名]
class APIs(QObject):
    """
    Class implementing an API storage entity.
    
    @signal apiPreparationFinished() emitted after the API preparation has finished
    @signal apiPreparationCancelled() emitted after the API preparation has been cancelled
    @signal apiPreparationStarted() emitted after the API preparation has started
    """
    def __init__(self, language, forPreparation = False, parent = None):
        """
        Constructor
        
        @param language language of the APIs object (string)
        @param forPreparation flag indicating this object is just needed
            for a preparation process (boolean)
        @param parent reference to the parent object (QObject)
        """
        QObject.__init__(self, parent)
        self.setObjectName("APIs_%s" % language)
        
        self.__inPreparation = False
        self.__language = language
        self.__forPreparation = forPreparation
        self.__lexer = Lexers.getLexer(self.__language)
        self.__apifiles = Preferences.getEditorAPI(self.__language)
        self.__apifiles.sort()
        if self.__lexer is None:
            self.__apis = None
        else:
            self.__apis = QsciAPIs(self.__lexer)
            self.connect(self.__apis, SIGNAL("apiPreparationFinished()"),
                         self.__apiPreparationFinished)
            self.connect(self.__apis, SIGNAL("apiPreparationCancelled()"),
                         self.__apiPreparationCancelled)
            self.connect(self.__apis, SIGNAL("apiPreparationStarted()"),
                         self.__apiPreparationStarted)
            self.__loadAPIs()
        
    def __loadAPIs(self):
        """
        Private method to load the APIs.
        """
        if self.__apis.isPrepared():
            # load a prepared API file
            if not self.__forPreparation and Preferences.getEditor("AutoPrepareAPIs"):
                self.prepareAPIs()
            self.__apis.loadPrepared()
        else:
            # load the raw files and prepare the API file
            if not self.__forPreparation and Preferences.getEditor("AutoPrepareAPIs"):
                self.prepareAPIs(ondemand = True)
    
    def reloadAPIs(self):
        """
        Public method to reload the API information.
        """
        if not self.__forPreparation and Preferences.getEditor("AutoPrepareAPIs"):
            self.prepareAPIs()
        self.__loadAPIs()
    
    def getQsciAPIs(self):
        """
        Public method to get a reference to QsciAPIs object.
        
        @return reference to the QsciAPIs object (QsciAPIs)
        """
        if not self.__forPreparation and Preferences.getEditor("AutoPrepareAPIs"):
            self.prepareAPIs()
        return self.__apis
    
    def __apiPreparationFinished(self):
        """
        Private method called to save an API, after it has been prepared.
        """
        res = self.__apis.savePrepared()
        self.__inPreparation = False
        self.emit(SIGNAL('apiPreparationFinished()'))
    
    def __apiPreparationCancelled(self):
        """
        Private method called, after the API preparation process has been cancelled.
        """
        self.__inPreparation = False
        self.emit(SIGNAL('apiPreparationCancelled()'))
    
    def __apiPreparationStarted(self):
        """
        Private method called, when the API preparation process started.
        """
        self.__inPreparation = True
        self.emit(SIGNAL('apiPreparationStarted()'))
    
    def prepareAPIs(self, ondemand = False, rawList = None):
        """
        Public method to prepare the APIs if necessary.
        
        @keyparam ondemand flag indicating a requested preparation (boolean)
        @keyparam rawList list of raw API files (QStringList)
        """
        if self.__apis is None or self.__inPreparation:
#.........这里部分代码省略.........
开发者ID:usc-bbdl,项目名称:R01_HSC_cadaver_system,代码行数:103,代码来源:APIsManager.py

示例11: ScriptEdit

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [as 别名]

#.........这里部分代码省略.........
        settings = QSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', size))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setStretch(QFont.SemiCondensed)
        self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        self.defaultFont.setBold(False)

        self.boldFont = QFont(self.defaultFont)
        self.boldFont.setBold(True)

        self.italicFont = QFont(self.defaultFont)
        self.italicFont.setItalic(True)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

    def initShortcuts(self):
        (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16)

        # Disable some shortcuts
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl
                           + shift)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)

        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)

        # Use Ctrl+Space for autocompletion
        self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL
                                                           + Qt.Key_Space), self)
        self.shortcutAutocomplete.setContext(Qt.WidgetShortcut)
        self.shortcutAutocomplete.activated.connect(self.autoComplete)

    def autoComplete(self):
        self.autoCompleteFromAll()

    def setLexerType(self, lexerType):
        self.lexerType = lexerType
        self.initLexer()

    def initLexer(self):
        if self.lexerType == self.LEXER_PYTHON:
            self.lexer = QsciLexerPython()

            colorDefault = QColor('#2e3436')
            colorComment = QColor('#c00')
            colorCommentBlock = QColor('#3465a4')
            colorNumber = QColor('#4e9a06')
            colorType = QColor('#4e9a06')
            colorKeyword = QColor('#204a87')
            colorString = QColor('#ce5c00')

            self.lexer.setDefaultFont(self.defaultFont)
            self.lexer.setDefaultColor(colorDefault)

            self.lexer.setColor(colorComment, 1)
            self.lexer.setColor(colorNumber, 2)
            self.lexer.setColor(colorString, 3)
            self.lexer.setColor(colorString, 4)
            self.lexer.setColor(colorKeyword, 5)
            self.lexer.setColor(colorString, 6)
            self.lexer.setColor(colorString, 7)
            self.lexer.setColor(colorType, 8)
            self.lexer.setColor(colorCommentBlock, 12)
            self.lexer.setColor(colorString, 15)

            self.lexer.setFont(self.italicFont, 1)
            self.lexer.setFont(self.boldFont, 5)
            self.lexer.setFont(self.boldFont, 8)
            self.lexer.setFont(self.italicFont, 12)

            self.api = QsciAPIs(self.lexer)

            settings = QSettings()
            useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI',
                                                True))
            if useDefaultAPI:
                # Load QGIS API shipped with Python console
                self.api.loadPrepared(
                    os.path.join(QgsApplication.pkgDataPath(),
                                 'python', 'qsci_apis', 'pyqgis.pap'))
            else:
                # Load user-defined API files
                apiPaths = settings.value('pythonConsole/userAPI', [])
                for path in apiPaths:
                    self.api.load(path)
                self.api.prepare()
                self.lexer.setAPIs(self.api)
        elif self.lexerType == self.LEXER_R:
            # R lexer
            self.lexer = LexerR()

        self.setLexer(self.lexer)
开发者ID:HeatherHillers,项目名称:QGIS,代码行数:104,代码来源:ScriptEdit.py

示例12: PythonEdit

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [as 别名]

#.........这里部分代码省略.........
            """Import QtGui class"""
            self.append('from PyQt4.QtGui import *')
            self.move_cursor_to_end()
        self.setFocus()

    def setLexers(self):
        from qgis.core import QgsApplication
        
        self.lexer = QsciLexerPython()
        settings = QSettings()
        loadFont = settings.value("pythonConsole/fontfamilytext", "Monospace").toString()
        fontSize = settings.value("pythonConsole/fontsize", 10).toInt()[0]
        
        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        
        self.lexer.setDefaultFont(font)
        self.lexer.setColor(Qt.red, 1)
        self.lexer.setColor(Qt.darkGreen, 5)
        self.lexer.setColor(Qt.darkBlue, 15)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)
        
        self.api = QsciAPIs(self.lexer)
        chekBoxAPI = settings.value( "pythonConsole/preloadAPI" ).toBool()
        if chekBoxAPI:
            self.api.loadPrepared( QgsApplication.pkgDataPath() + "/python/qsci_apis/pyqgis_master.pap" )
        else:
            apiPath = settings.value("pythonConsole/userAPI").toStringList()
            for i in range(0, len(apiPath)):
                self.api.load(QString(unicode(apiPath[i])))        
            self.api.prepare()
            self.lexer.setAPIs(self.api)

        self.setLexer(self.lexer)
            
    ## TODO: show completion list for file and directory
    
    def completion_list_selected(self, id, txt):
        if id == 1:
            txt = unicode(txt)
            # get current cursor position 
            line, pos = self.getCursorPosition()
            selCmdLength = self.text(line).length()
            # select typed text
            self.setSelection(line, 4, line, selCmdLength)
            self.removeSelectedText()
            self.insert(txt)

    def insertInitText(self):
        #self.setLexers(False)
        txtInit = QCoreApplication.translate("PythonConsole",
                                             "## To access Quantum GIS environment from this console\n"
                                             "## use qgis.utils.iface object (instance of QgisInterface class). Read help for more info.\n\n")
        initText = self.setText(txtInit)

    def getText(self):
        """ Get the text as a unicode string. """
        value = self.getBytes().decode('utf-8')
        # print (value) printing can give an error because the console font
        # may not have all unicode characters
        return value

    def getBytes(self):
开发者ID:endmax,项目名称:Quantum-GIS,代码行数:70,代码来源:console_sci.py

示例13: CommandShell

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [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()
#.........这里部分代码省略.........
开发者ID:g-sherman,项目名称:qgiscommand,代码行数:103,代码来源:qgiscommand.py

示例14: MultipleCppEditor

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [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() + '" ?',
#.........这里部分代码省略.........
开发者ID:JeraldPogi,项目名称:philrobotics-projects,代码行数:103,代码来源:editor.py

示例15: QsciEditor

# 需要导入模块: from PyQt4.Qsci import QsciAPIs [as 别名]
# 或者: from PyQt4.Qsci.QsciAPIs import prepare [as 别名]

#.........这里部分代码省略.........
            self.setMarginLineNumbers(i_margin, False)
            self.setMarginMarkerMask(i_margin, 0)
            self.setMarginSensitivity(i_margin, False)
        if linenumbers:
            # 1: Line numbers margin
            self.setMarginLineNumbers(1, True)
            self.update_line_numbers_margin()
            if code_analysis:
                # 2: Errors/warnings margin
                mask = (1 << self.error) | (1 << self.warning)
                self.setMarginSensitivity(0, True)
                self.setMarginMarkerMask(0, mask)
                self.setMarginWidth(0, 14)
                self.connect(self,
                     SIGNAL('marginClicked(int,int,Qt::KeyboardModifiers)'),
                     self.__margin_clicked)
        if code_folding:
            # 0: Folding margin
            self.setMarginWidth(2, 14)
            self.setFolding(QsciScintilla.BoxedFoldStyle)                
        # Colors
        fcol = CONF.get('scintilla', 'margins/foregroundcolor')
        bcol = CONF.get('scintilla', 'margins/backgroundcolor')
        if fcol:
            self.setMarginsForegroundColor(QColor(fcol))
        if bcol:
            self.setMarginsBackgroundColor(QColor(bcol))
        fcol = CONF.get('scintilla', 'foldmarginpattern/foregroundcolor')
        bcol = CONF.get('scintilla', 'foldmarginpattern/backgroundcolor')
        if fcol and bcol:
            self.setFoldMarginColors(QColor(fcol), QColor(bcol))
        
    def setup_api(self):
        """Load and prepare API"""
        if self.lexer() is None:
            return
        self.api = QsciAPIs(self.lexer())
        is_api_ready = False
        api_path = CONF.get('editor', 'api')
        if not os.path.isfile(api_path):
            return False
        api_stat = CONF.get('editor', 'api_stat', None)
        current_api_stat = os.stat(api_path)
        if (api_stat is not None) and (api_stat == current_api_stat):
            if self.api.isPrepared():
                is_api_ready = self.api.loadPrepared()
        else:
            CONF.set('editor', 'api_stat', current_api_stat)
        if not is_api_ready:
            if self.api.load(api_path):
                self.api.prepare()
                self.connect(self.api, SIGNAL("apiPreparationFinished()"),
                             self.api.savePrepared)
        return is_api_ready
    
    def set_whitespace_visible(self, state):
        """Show/hide whitespace"""
        if state:
            self.setWhitespaceVisibility(QsciScintilla.WsVisible)
        else:
            self.setWhitespaceVisibility(QsciScintilla.WsInvisible)
    
    def set_eol_chars_visible(self, state):
        """Show/hide EOL characters"""
        self.setEolVisibility(state)
    
开发者ID:Brainsciences,项目名称:luminoso,代码行数:69,代码来源:qscieditor.py


注:本文中的PyQt4.Qsci.QsciAPIs.prepare方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。