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


Python QShortcut.setContext方法代码示例

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


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

示例1: _shortcutHelper

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
 def _shortcutHelper(self, keySequence, group, description, parent, function, context = None, enabled = None):
     shortcut = QShortcut(QKeySequence(keySequence), parent, member=function, ambiguousMember=function)
     if context != None:
         shortcut.setContext(context)
     if enabled != None:
         shortcut.setEnabled(True)
     return shortcut, group, description
开发者ID:lcroitor,项目名称:volumeeditor,代码行数:9,代码来源:volumeEditorWidget.py

示例2: __init__

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
 def __init__(self, parent, actions=None):
     QTabWidget.__init__(self, parent)
     tab_bar = TabsBase(self, parent)
     self.connect(tab_bar, SIGNAL('move_tab(int,int)'), self.move_tab)
     self.connect(tab_bar, SIGNAL('move_tab(long,int,int)'),
                  self.move_tab_from_another_tabwidget)
     self.setTabBar(tab_bar)
     self.menu = QMenu(self)
     if actions:
         add_actions(self.menu, actions)
     self.index_history = []
     self.connect(self, SIGNAL('currentChanged(int)'),
                  self.__current_changed)
     tabsc = QShortcut(QKeySequence("Ctrl+Tab"), parent, self.tab_navigate)
     tabsc.setContext(Qt.WidgetWithChildrenShortcut)
开发者ID:Brainsciences,项目名称:luminoso,代码行数:17,代码来源:tabs.py

示例3: DockWidget

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
class DockWidget(QDockWidget):
    """Extended QDockWidget for Enki main window
    """
    def __init__(self, *args):
        QDockWidget.__init__(self, *args)

        self._showAction = None
        self._titleBar = _TitleBar( self )
        self.setTitleBarWidget( self._titleBar )
        
        self._closeShortcut = QShortcut( QKeySequence( "Esc" ), self )
        self._closeShortcut.setContext( Qt.WidgetWithChildrenShortcut )
        self._closeShortcut.activated.connect(self._hide)

    def showAction(self):
        """Action shows the widget and set focus on it.
        
        Add this action to the main menu
        """
        if  not self._showAction :
            self._showAction = QAction(self.windowIcon(), self.windowTitle(), self)
            self._showAction.triggered.connect(self.show)
            self._showAction.triggered.connect(self._handleFocusProxy)

        return self._showAction

    def titleBarWidget(self):
        """QToolBar on the title.
        
        You may add own actions to this tool bar
        """
        # method was added only for documenting
        return QDockWidget.titleBarWidget(self)
    
    def _handleFocusProxy(self):
        """Set focus to focus proxy.
        Called after widget has been shown
        """
        if self.focusProxy() is not None:
            self.setFocus()

    def _hide(self):
        """Hide and return focus to MainWindow focus proxy
        """
        self.hide()
        if self.parent() is not None and \
           self.parent().focusProxy() is not None:
            self.parent().focusProxy().setFocus()
开发者ID:daffodil,项目名称:enki,代码行数:50,代码来源:dockwidget.py

示例4: __init__

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
 def __init__(self, parent, mainwin):
     QPlainTextEdit.__init__(self, parent)
     self.mainwin = mainwin
     self.setObjectName("restedit")
     self._formats = {}
     self.textChanged.connect(self._restedit_update)
     self.blockCountChanged.connect(self._blockcount_update)
     shortcut = QShortcut(QKeySequence("Ctrl+T"), self)
     shortcut.activated.connect(self._choose_font)
     shortcut = QShortcut(QKeySequence.ZoomIn, self)
     shortcut.activated.connect(self._zoom_in)
     shortcut.setContext(Qt.WidgetShortcut)
     shortcut = QShortcut(QKeySequence.ZoomOut, self)
     shortcut.activated.connect(self._zoom_out)
     shortcut.setContext(Qt.WidgetShortcut)
     self._doc = QApplication.instance().rest
     self._last_warnings = {} # should be moved to the document
开发者ID:eblot,项目名称:ezsphinx,代码行数:19,代码来源:restedit.py

示例5: __init__

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
 def __init__(self, parent, actions=None):
     BaseTabs.__init__(self, parent, actions)
     tab_bar = TabBar(self, parent)
     self.connect(tab_bar, SIGNAL('move_tab(int,int)'), self.move_tab)
     self.connect(tab_bar, SIGNAL('move_tab(long,int,int)'),
                  self.move_tab_from_another_tabwidget)
     self.setTabBar(tab_bar)
     self.index_history = []
     self.connect(self, SIGNAL('currentChanged(int)'),
                  self.__current_changed)
     tabsc = QShortcut(QKeySequence("Ctrl+Tab"), parent, self.tab_navigate)
     tabsc.setContext(Qt.WidgetWithChildrenShortcut)
     # Browsing tabs button
     browse_button = create_toolbutton(self,
                                       icon=get_icon("browse_tab.png"),
                                       tip=translate("Tabs", "Browse tabs"))
     self.browse_tabs_menu = QMenu(self)
     browse_button.setMenu(self.browse_tabs_menu)
     browse_button.setPopupMode(browse_button.InstantPopup)
     self.connect(self.browse_tabs_menu, SIGNAL("aboutToShow()"),
                  self.update_browse_tabs_menu)
     self.setCornerWidget(browse_button)
开发者ID:cheesinglee,项目名称:spyder,代码行数:24,代码来源:tabs.py

示例6: __init__

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
 def __init__(self, *args, **kw):
     # To override the Qt widget used by RichIPythonWidget
     self.custom_control = IPythonControlWidget
     self.custom_page_control = IPythonPageControlWidget
     super(SMIPythonWidget, self).__init__(*args, **kw)
     self.set_background_color()
     
     # --- Spyder variables ---
     self.ipyclient = None
     
     # --- Keyboard shortcuts ---
     inspectsc = QShortcut(QKeySequence("Ctrl+I"), self,
                           self._control.inspect_current_object)
     inspectsc.setContext(Qt.WidgetWithChildrenShortcut)
     clear_consolesc = QShortcut(QKeySequence("Ctrl+L"), self,
                                 self.clear_console)
     clear_consolesc.setContext(Qt.WidgetWithChildrenShortcut)
     
     # --- IPython variables ---
     # To send an interrupt signal to the Spyder kernel
     self.custom_interrupt = True
     
     # To restart the Spyder kernel in case it dies
     self.custom_restart = True
开发者ID:koll00,项目名称:Gui_SM,代码行数:26,代码来源:ipython.py

示例7: __init__

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
 def __init__(self, parent, mainwin):
     QWebView.__init__(self, parent)
     self.mainwin = mainwin
     self.setUrl(QUrl("about:blank"))
     self.setObjectName("webview")
     self.setTextSizeMultiplier(self.ZOOM_DEFAULT)
     shortcut = QShortcut(QKeySequence.ZoomIn, self)
     shortcut.activated.connect(self._zoom_in)
     shortcut.setContext(Qt.WidgetShortcut)
     shortcut = QShortcut(QKeySequence(Qt.CTRL | Qt.Key_Equal), self)
     shortcut.activated.connect(self._zoom_neutral)
     shortcut.setContext(Qt.WidgetShortcut)
     shortcut = QShortcut(QKeySequence.ZoomOut, self)
     shortcut.activated.connect(self._zoom_out)
     shortcut.setContext(Qt.WidgetShortcut)
开发者ID:eblot,项目名称:ezsphinx,代码行数:17,代码来源:web.py

示例8: __init__

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]

#.........这里部分代码省略.........
        
        self.previous_button = create_toolbutton(self,
                                             triggered=self.find_previous,
                                             icon=get_std_icon("ArrowBack"))
        self.next_button = create_toolbutton(self,
                                             triggered=self.find_next,
                                             icon=get_std_icon("ArrowForward"))
        self.connect(self.next_button, SIGNAL('clicked()'),
                     self.update_search_combo)
        self.connect(self.previous_button, SIGNAL('clicked()'),
                     self.update_search_combo)

        self.re_button = create_toolbutton(self, icon=get_icon("advanced.png"),
                                           tip=_("Regular expression"))
        self.re_button.setCheckable(True)
        self.connect(self.re_button, SIGNAL("toggled(bool)"),
                     lambda state: self.find())
        
        self.case_button = create_toolbutton(self,
                                             icon=get_icon("upper_lower.png"),
                                             tip=_("Case Sensitive"))
        self.case_button.setCheckable(True)
        self.connect(self.case_button, SIGNAL("toggled(bool)"),
                     lambda state: self.find())
                     
        self.words_button = create_toolbutton(self,
                                              icon=get_icon("whole_words.png"),
                                              tip=_("Whole words"))
        self.words_button.setCheckable(True)
        self.connect(self.words_button, SIGNAL("toggled(bool)"),
                     lambda state: self.find())
                     
        self.highlight_button = create_toolbutton(self,
                                              icon=get_icon("highlight.png"),
                                              tip=_("Highlight matches"))
        self.highlight_button.setCheckable(True)
        self.connect(self.highlight_button, SIGNAL("toggled(bool)"),
                     self.toggle_highlighting)

        hlayout = QHBoxLayout()
        self.widgets = [self.close_button, self.search_text,
                        self.previous_button, self.next_button,
                        self.re_button, self.case_button, self.words_button,
                        self.highlight_button]
        for widget in self.widgets[1:]:
            hlayout.addWidget(widget)
        glayout.addLayout(hlayout, 0, 1)

        # Replace layout
        replace_with = QLabel(_("Replace with:"))
        self.replace_text = PatternComboBox(self, adjust_to_minimum=False,
                                            tip=_("Replace string"))
        
        self.replace_button = create_toolbutton(self,
                                     text=_("Replace/find"),
                                     icon=get_std_icon("DialogApplyButton"),
                                     triggered=self.replace_find,
                                     text_beside_icon=True)
        self.connect(self.replace_button, SIGNAL('clicked()'),
                     self.update_replace_combo)
        self.connect(self.replace_button, SIGNAL('clicked()'),
                     self.update_search_combo)
        
        self.all_check = QCheckBox(_("Replace all"))
        
        self.replace_layout = QHBoxLayout()
        widgets = [replace_with, self.replace_text, self.replace_button,
                   self.all_check]
        for widget in widgets:
            self.replace_layout.addWidget(widget)
        glayout.addLayout(self.replace_layout, 1, 1)
        self.widgets.extend(widgets)
        self.replace_widgets = widgets
        self.hide_replace()
        
        self.search_text.setTabOrder(self.search_text, self.replace_text)
        
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        self.findnext_sc = QShortcut(QKeySequence("F3"), parent,
                                     self.find_next)
        self.findnext_sc.setContext(Qt.WidgetWithChildrenShortcut)
        self.findprev_sc = QShortcut(QKeySequence("Shift+F3"), parent,
                                     self.find_previous)
        self.findprev_sc.setContext(Qt.WidgetWithChildrenShortcut)
        self.togglefind_sc = QShortcut(QKeySequence("Ctrl+F"), parent,
                                       self.show)
        self.togglefind_sc.setContext(Qt.WidgetWithChildrenShortcut)
        self.togglereplace_sc = QShortcut(QKeySequence("Ctrl+H"), parent,
                                          self.toggle_replace_widgets)
        self.togglereplace_sc.setContext(Qt.WidgetWithChildrenShortcut)
        
        escape_sc = QShortcut(QKeySequence("Escape"), parent, self.hide)
        escape_sc.setContext(Qt.WidgetWithChildrenShortcut)

        self.highlight_timer = QTimer(self)
        self.highlight_timer.setSingleShot(True)
        self.highlight_timer.setInterval(1000)
        self.connect(self.highlight_timer, SIGNAL("timeout()"),
                     self.highlight_matches)
开发者ID:koll00,项目名称:Gui_SM,代码行数:104,代码来源:findreplace.py

示例9: SearchWidget

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]

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

        self.cbSearch.setCompleter(None)
        self.cbReplace.setCompleter(None)
        self.cbMask.setCompleter(None)

        self.fsModel = QDirModel(self.cbPath.lineEdit())
        self.fsModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        self.cbPath.lineEdit().setCompleter(QCompleter(self.fsModel, self.cbPath.lineEdit()))
        # TODO QDirModel is deprecated but QCompleter does not yet handle
        # QFileSystemodel - please update when possible."""
        self.cbSearch.setCompleter(None)
        self.pbSearchStop.setVisible(False)
        self.pbReplaceCheckedStop.setVisible(False)

        self._progress = QProgressBar(self)
        self._progress.setAlignment(Qt.AlignCenter)
        self._progress.setToolTip(self.tr("Search in progress..."))
        self._progress.setMaximumSize(QSize(80, 16))
        core.mainWindow().statusBar().insertPermanentWidget(1, self._progress)
        self._progress.setVisible(False)

        # cd up action
        self.tbCdUp = QToolButton(self.cbPath.lineEdit())
        self.tbCdUp.setIcon(QIcon(":/enkiicons/go-up.png"))
        self.tbCdUp.setCursor(Qt.ArrowCursor)
        self.tbCdUp.installEventFilter(self)  # for drawing button

        self.cbSearch.installEventFilter(self)  # for catching Tab and Shift+Tab
        self.cbReplace.installEventFilter(self)  # for catching Tab and Shift+Tab
        self.cbPath.installEventFilter(self)  # for catching Tab and Shift+Tab
        self.cbMask.installEventFilter(self)  # for catching Tab and Shift+Tab

        self._closeShortcut = QShortcut(QKeySequence("Esc"), self)
        self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut)
        self._closeShortcut.activated.connect(self.hide)

        # connections
        self.cbSearch.lineEdit().textChanged.connect(self._onSearchRegExpChanged)

        self.cbSearch.lineEdit().returnPressed.connect(self._onReturnPressed)
        self.cbReplace.lineEdit().returnPressed.connect(self._onReturnPressed)
        self.cbPath.lineEdit().returnPressed.connect(self._onReturnPressed)
        self.cbMask.lineEdit().returnPressed.connect(self._onReturnPressed)

        self.cbRegularExpression.stateChanged.connect(self._onSearchRegExpChanged)
        self.cbCaseSensitive.stateChanged.connect(self._onSearchRegExpChanged)

        self.tbCdUp.clicked.connect(self._onCdUpPressed)

        core.mainWindow().hideAllWindows.connect(self.hide)
        core.workspace().currentDocumentChanged.connect(
            lambda old, new: self.setVisible(self.isVisible() and new is not None)
        )

    def show(self):
        """Reimplemented function. Sends signal
        """
        super(SearchWidget, self).show()
        self.visibilityChanged.emit(self.isVisible())

    def hide(self):
        """Reimplemented function.
        Sends signal, returns focus to workspace
        """
        super(SearchWidget, self).hide()
        core.workspace().focusCurrentDocument()
开发者ID:rolandschulz,项目名称:enki,代码行数:70,代码来源:searchwidget.py

示例10: DockWidget

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
class DockWidget(QDockWidget):
    """Extended QDockWidget for Enki main window
    """

    closed = pyqtSignal()
    """
    closed()

    **Signal** emitted, when dock is closed
    """

    shown = pyqtSignal()
    """
    shown()

    **Signal** emitted, when dock is shown
    """

    def __init__(self, parentObject, windowTitle, windowIcon = QIcon(), shortcut = None):
        QDockWidget.__init__(self, parentObject)
        self._showAction = None

        self.setObjectName(str(self.__class__))
        self.setWindowTitle(windowTitle)

        if not windowIcon.isNull():
            self.setWindowIcon(windowIcon)
        if shortcut is not None:
            self.showAction().setShortcut(shortcut)

        self._titleBar = _TitleBar( self )
        self.setTitleBarWidget( self._titleBar )

        if shortcut is not None:
            toolTip = "Move focus with <b>%s</b>,<br/>close with <b>Esc</b>" % shortcut
        else:
            toolTip = "Close with <b>Esc</b>"
        self._titleBar.setToolTip(toolTip)

        self._closeShortcut = QShortcut( QKeySequence( "Esc" ), self )
        self._closeShortcut.setContext( Qt.WidgetWithChildrenShortcut )
        self._closeShortcut.activated.connect(self._close)

    def keyPressEvent(self, event):
        """Catch Esc. Not using QShortcut, because dock shall be closed,
        only if child widgets haven't catched Esc event
        """
        if event.key() == Qt.Key_Escape and \
           event.modifiers() == Qt.NoModifier:
            self._hide()
        else:
            QDockWidget.keyPressEvent(self, event)

    def showAction(self):
        """Action shows the widget and set focus on it.

        Add this action to the main menu
        """
        if  not self._showAction :
            self._showAction = QAction(self.windowIcon(), self.windowTitle(), self)
            self._showAction.triggered.connect(self.show)
            self._showAction.triggered.connect(self._handleFocusProxy)

        return self._showAction

    def titleBarWidget(self):
        """QToolBar on the title.

        You may add own actions to this tool bar
        """
        # method was added only for documenting
        return QDockWidget.titleBarWidget(self)

    def _handleFocusProxy(self):
        """Set focus to focus proxy.
        Called after widget has been shown
        """
        if self.focusProxy() is not None:
            self.setFocus()

    def _close(self):
        """Hide and return focus to MainWindow focus proxy
        """
        self.close()
        if self.parent() is not None and \
           self.parent().focusProxy() is not None:
            self.parent().focusProxy().setFocus()

    def closeEvent(self, event):
        """Widget was closed"""
        self.closed.emit()

    def showEvent(self, event):
        """Widget was shown"""
        self.shown.emit()
开发者ID:adjustive,项目名称:enki,代码行数:97,代码来源:dockwidget.py

示例11: QShortcut

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
    ui.browse_button.clicked.connect(container.browse)
    ui.vna_browse_button.clicked.connect(container.browse)

    ui.actionAbrir.triggered.connect(container.open_file)
    ui.actionGuardar.triggered.connect(container.save_file)
    ui.actionGuardar_como.triggered.connect(container.save_as_file)
    ui.actionSalir.triggered.connect(container.close)
    ui.actionCalibration.triggered.connect(container.launch_calibration)
    ui.actionCalibration_Presets.triggered.connect(container.launch_preset_calibration)
    ui.actionRI.triggered.connect(container.launch_ri)
    ui.actionContinuo_Alterno.triggered.connect(container.launch_conalt)

    ui.left_button.clicked.connect(container.move_left)
    left_shortcut = QShortcut(QKeySequence(QtCore.Qt.ControlModifier + QtCore.Qt.Key_Left), 
            ui.centralwidget)
    left_shortcut.setContext(QtCore.Qt.ApplicationShortcut)
    left_shortcut.activated.connect(container.move_left)

    ui.right_button.clicked.connect(container.move_right)
    right_shortcut = QShortcut(QKeySequence(QtCore.Qt.ControlModifier + QtCore.Qt.Key_Right),
            ui.centralwidget)
    right_shortcut.setContext(QtCore.Qt.ApplicationShortcut)
    right_shortcut.activated.connect(container.move_right)

    ui.all_checkbox.stateChanged.connect(container.checked_all)

    app.aboutToQuit.connect(container.save_ui)
    restore_ui(ui)
    window.show()
    sys.exit(app.exec_())
开发者ID:jsantos17,项目名称:Tesis,代码行数:32,代码来源:app.py

示例12: ShellOutputScintilla

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
class ShellOutputScintilla(QsciScintilla):

    def __init__(self, parent=None):
        super(ShellOutputScintilla, self).__init__(parent)
        self.parent = parent
        self.shell = self.parent.shell

        self.settings = QSettings()

        # Creates layout for message bar
        self.layout = QGridLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # messageBar instance
        self.infoBar = QgsMessageBar()
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # Enable non-ascii chars for editor
        self.setUtf8(True)

        sys.stdout = writeOut(self, sys.stdout)
        sys.stderr = writeOut(self, sys.stderr, "_traceback")

        self.insertInitText()
        self.refreshSettingsOutput()
        self.setReadOnly(True)

        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)
        # Margin 0 is used for line numbers
        self.setMarginWidth(0, 0)
        self.setMarginWidth(1, 0)
        self.setMarginWidth(2, 0)
        #fm = QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(1, "00000")
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor("#3E3EE3"))
        self.setMarginsBackgroundColor(QColor("#f9f9f9"))
        self.setCaretLineVisible(True)
        self.setCaretWidth(0)

        self.setMinimumHeight(120)

        self.setWrapMode(QsciScintilla.WrapCharacter)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self)
        self.runScut.setContext(Qt.WidgetShortcut)
        self.runScut.activated.connect(self.enteredSelected)
        # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view
        self.copyShortcut = QShortcut(QKeySequence.Copy, self)
        self.copyShortcut.activated.connect(self.copy)
        self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self)
        self.selectAllShortcut.activated.connect(self.selectAll)

    def insertInitText(self):
        txtInit = QCoreApplication.translate("PythonConsole",
                                             "Python Console \n"
                                             "Use iface to access QGIS API interface or Type help(iface) for more info")

        ## some translation string for the console header ends without '\n'
        ## and the first command in console will be appended at the header text.
        ## The following code add a '\n' at the end of the string if not present.
        if txtInit.endswith('\n'):
            self.setText(txtInit)
        else:
            self.setText(txtInit + '\n')

    def refreshSettingsOutput(self):
        # Set Python lexer
        self.setLexers()
        caretLineColor = self.settings.value("pythonConsole/caretLineColor", QColor("#fcf3ed"))
        cursorColor = self.settings.value("pythonConsole/cursorColor", QColor(Qt.black))
        self.setCaretLineBackgroundColor(caretLineColor)
        self.setCaretForegroundColor(cursorColor)

    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
        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.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black))))
#.........这里部分代码省略.........
开发者ID:HeatherHillers,项目名称:QGIS,代码行数:103,代码来源:console_output.py

示例13: PythonShellWidget

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
class PythonShellWidget(TracebackLinksMixin, ShellBaseWidget,
                        InspectObjectMixin):
    """Python shell widget"""
    QT_CLASS = ShellBaseWidget

    INITHISTORY = ['# -*- coding: utf-8 -*-',
                   '# *** Spyder Python Console History Log ***',]
    SEPARATOR = '%s##---(%s)---' % (os.linesep*2, time.ctime())
    
    def __init__(self, parent, history_filename, profile=False):
        ShellBaseWidget.__init__(self, parent, history_filename, profile)
        TracebackLinksMixin.__init__(self)
        InspectObjectMixin.__init__(self)

        # Local shortcuts
        self.inspectsc = QShortcut(QKeySequence("Ctrl+I"), self,
                                   self.inspect_current_object)
        self.inspectsc.setContext(Qt.WidgetWithChildrenShortcut)
        
    def get_shortcut_data(self):
        """
        Returns shortcut data, a list of tuples (shortcut, text, default)
        shortcut (QShortcut or QAction instance)
        text (string): action/shortcut description
        default (string): default key sequence
        """
        return [
                (self.inspectsc, "Inspect current object", "Ctrl+I"),
                ]


    #------ Context menu
    def setup_context_menu(self):
        """Reimplements ShellBaseWidget method"""
        ShellBaseWidget.setup_context_menu(self)
        self.copy_without_prompts_action = create_action(self,
                                     _("Copy without prompts"),
                                     icon=get_icon('copywop.png'),
                                     triggered=self.copy_without_prompts)
        clear_line_action = create_action(self, _("Clear line"),
                                     QKeySequence("Shift+Escape"),
                                     icon=get_icon('eraser.png'),
                                     tip=_("Clear line"),
                                     triggered=self.clear_line)
        clear_action = create_action(self, _("Clear shell"),
                                     QKeySequence("Ctrl+L"),
                                     icon=get_icon('clear.png'),
                                     tip=_("Clear shell contents "
                                           "('cls' command)"),
                                     triggered=self.clear_terminal)
        add_actions(self.menu, (self.copy_without_prompts_action,
                    clear_line_action, clear_action))
          
    def contextMenuEvent(self, event):
        """Reimplements ShellBaseWidget method"""
        state = self.has_selected_text()
        self.copy_without_prompts_action.setEnabled(state)
        ShellBaseWidget.contextMenuEvent(self, event)
        
    def copy_without_prompts(self):
        """Copy text to clipboard without prompts"""
        text = self.get_selected_text()
        lines = text.split(os.linesep)
        for index, line in enumerate(lines):
            if line.startswith('>>> ') or line.startswith('... '):
                lines[index] = line[4:]
        text = os.linesep.join(lines)
        QApplication.clipboard().setText(text)
    
    
    #------ Key handlers
    def postprocess_keyevent(self, event):
        """Process keypress event"""
        ShellBaseWidget.postprocess_keyevent(self, event)
        if QToolTip.isVisible():
            _event, _text, key, _ctrl, _shift = restore_keyevent(event)
            self.hide_tooltip_if_necessary(key)
                
    def _key_other(self, text):
        """1 character key"""
        if self.is_completion_widget_visible():
            self.completion_text += text
                
    def _key_backspace(self, cursor_position):
        """Action for Backspace key"""
        if self.has_selected_text():
            self.check_selection()
            self.remove_selected_text()
        elif self.current_prompt_pos == cursor_position:
            # Avoid deleting prompt
            return
        elif self.is_cursor_on_last_line():
            self.stdkey_backspace()
            if self.is_completion_widget_visible():
                # Removing only last character because if there was a selection
                # the completion widget would have been canceled
                self.completion_text = self.completion_text[:-1]
                
    def _key_tab(self):
        """Action for TAB key"""
#.........这里部分代码省略.........
开发者ID:koll00,项目名称:Gui_SM,代码行数:103,代码来源:shell.py

示例14: ShellScintilla

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [as 别名]
class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):

    def __init__(self, parent=None):
        super(ShellScintilla, self).__init__(parent)
        code.InteractiveInterpreter.__init__(self, locals=None)

        self.parent = parent

        self.opening = ['(', '{', '[', "'", '"']
        self.closing = [')', '}', ']', "'", '"']

        self.settings = QSettings()

        # Enable non-ascii chars for editor
        self.setUtf8(True)

        self.new_input_line = True

        self.setMarginWidth(0, 0)
        self.setMarginWidth(1, 0)
        self.setMarginWidth(2, 0)

        self.buffer = []

        self.displayPrompt(False)

        for line in _init_commands:
            self.runsource(line)

        self.history = []
        self.historyIndex = 0
        # Read history command file
        self.readHistoryFile()

        self.historyDlg = HistoryDialog(self)

        # Brace matching: enable for a brace immediately before or after
        # the current position
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        self.setMatchedBraceBackgroundColor(QColor("#b7f907"))

        # Current line visible with special background color
        self.setCaretWidth(2)

        self.refreshSettingsShell()

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented
        # here: http://www.scintilla.org/ScintillaDoc.html)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        # not too small
        #self.setMinimumSize(500, 300)

        self.setWrapMode(QsciScintilla.WrapCharacter)
        self.SendScintilla(QsciScintilla.SCI_EMPTYUNDOBUFFER)

        ## Disable command key
        ctrl, shift = self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('Z') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('Y') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift)

        ## New QShortcut = ctrl+space/ctrl+alt+space for Autocomplete
        self.newShortcutCSS = QShortcut(QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Space), self)
        self.newShortcutCAS = QShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_Space), self)
        self.newShortcutCSS.setContext(Qt.WidgetShortcut)
        self.newShortcutCAS.setContext(Qt.WidgetShortcut)
        self.newShortcutCAS.activated.connect(self.autoCompleteKeyBinding)
        self.newShortcutCSS.activated.connect(self.showHistory)

    def _setMinimumHeight(self):
        fnt = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fntSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
        fm = QFontMetrics(QFont(fnt, fntSize))

        self.setMinimumHeight(fm.height() + 10)

    def refreshSettingsShell(self):
        # Set Python lexer
        self.setLexers()
        threshold = self.settings.value("pythonConsole/autoCompThreshold", 2, type=int)
        self.setAutoCompletionThreshold(threshold)
        radioButtonSource = self.settings.value("pythonConsole/autoCompleteSource", 'fromAPI')
        autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabled", True, type=bool)
        if autoCompEnabled:
            if radioButtonSource == 'fromDoc':
                self.setAutoCompletionSource(self.AcsDocument)
            elif radioButtonSource == 'fromAPI':
                self.setAutoCompletionSource(self.AcsAPIs)
            elif radioButtonSource == 'fromDocAPI':
                self.setAutoCompletionSource(self.AcsAll)
        else:
            self.setAutoCompletionSource(self.AcsNone)

        cursorColor = self.settings.value("pythonConsole/cursorColor", QColor(Qt.black))
        self.setCaretForegroundColor(cursorColor)
#.........这里部分代码省略.........
开发者ID:Geoneer,项目名称:QGIS,代码行数:103,代码来源:console_sci.py

示例15: ScriptEdit

# 需要导入模块: from PyQt4.QtGui import QShortcut [as 别名]
# 或者: from PyQt4.QtGui.QShortcut import setContext [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


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