def init_kernel_menu(self): self.kernel_menu = self.menuBar().addMenu("&Kernel") # Qt on OSX maps Ctrl to Cmd, and Meta to Ctrl # keep the signal shortcuts to ctrl, rather than # platform-default like we do elsewhere. ctrl = "Meta" if sys.platform == 'darwin' else "Ctrl" self.interrupt_kernel_action = QtGui.QAction( "Interrupt current Kernel", self, triggered=self.interrupt_kernel_active_frontend, shortcut=ctrl + "+C", ) self.add_menu_action(self.kernel_menu, self.interrupt_kernel_action) self.restart_kernel_action = QtGui.QAction( "Restart current Kernel", self, triggered=self.restart_kernel_active_frontend, shortcut=ctrl + "+.", ) self.add_menu_action(self.kernel_menu, self.restart_kernel_action) self.kernel_menu.addSeparator()
def get_font(family, fallback=None): """Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object """ font = QtGui.QFont(family) # Check whether we got what we wanted using QFontInfo, since exactMatch() # is overly strict and returns false in too many cases. font_info = QtGui.QFontInfo(font) if fallback is not None and font_info.family() != family: font = QtGui.QFont(fallback) return font
def init_kernel_menu(self): self.kernel_menu = self.menuBar().addMenu("&Kernel") # Qt on OSX maps Ctrl to Cmd, and Meta to Ctrl # keep the signal shortcuts to ctrl, rather than # platform-default like we do elsewhere. ctrl = "Meta" if sys.platform == 'darwin' else "Ctrl" self.interrupt_kernel_action = QtGui.QAction("&Interrupt current Kernel", self, triggered=self.interrupt_kernel_active_frontend, shortcut=ctrl+"+C", ) self.add_menu_action(self.kernel_menu, self.interrupt_kernel_action) self.restart_kernel_action = QtGui.QAction("&Restart current Kernel", self, triggered=self.restart_kernel_active_frontend, shortcut=ctrl+"+.", ) self.add_menu_action(self.kernel_menu, self.restart_kernel_action) self.kernel_menu.addSeparator() self.confirm_restart_kernel_action = QtGui.QAction("&Confirm kernel restart", self, checkable=True, checked=self.active_frontend.confirm_restart, triggered=self.toggle_confirm_restart_active_frontend ) self.add_menu_action(self.kernel_menu, self.confirm_restart_kernel_action) self.tab_widget.currentChanged.connect(self.update_restart_checkbox)
def svg_to_image(string, size=None): """ Convert a SVG document to a QImage. Parameters: ----------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises: ------- ValueError If an invalid SVG string is provided. Returns: -------- A QImage of format QImage.Format_ARGB32. """ if isinstance(string, unicode_type): string = string.encode('utf-8') renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string)) if not renderer.isValid(): raise ValueError('Invalid SVG data.') if size is None: size = renderer.defaultSize() image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32) painter = QtGui.QPainter(image) renderer.render(painter) return image
def __init__(self, parent=None): super(ImportDialog, self).__init__(parent) from globusonline.catalog.client.examples.catalog_wrapper import CatalogWrapper token_file = os.path.join(os.path.expanduser('~'), '.nexpy', 'globusonline', 'gotoken.txt') self.wrap = CatalogWrapper(token='file', token_file=token_file) _, self.catalogs = self.wrap.catalogClient.get_catalogs() catalog_layout = QtGui.QHBoxLayout() self.catalog_box = QtGui.QComboBox() for catalog in self.catalogs: try: self.catalog_box.addItem(catalog['config']['name']) except: pass self.catalog_box.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) catalog_button = QtGui.QPushButton("Choose Catalog") catalog_button.clicked.connect(self.get_catalog) catalog_layout.addWidget(self.catalog_box) catalog_layout.addWidget(catalog_button) self.layout = QtGui.QVBoxLayout() self.layout.addLayout(catalog_layout) self.layout.addWidget(self.close_buttons()) self.setLayout(self.layout) self.setWindowTitle("Import " + str(filetype))
def init_window_menu(self): self.window_menu = self.menuBar().addMenu("&Window") if sys.platform == 'darwin': # add min/maximize actions to OSX, which lacks default bindings. self.minimizeAct = QtGui.QAction("Mini&mize", self, shortcut="Ctrl+m", statusTip="Minimize the window/Restore Normal Size", triggered=self.toggleMinimized) # maximize is called 'Zoom' on OSX for some reason self.maximizeAct = QtGui.QAction("&Zoom", self, shortcut="Ctrl+Shift+M", statusTip="Maximize the window/Restore Normal Size", triggered=self.toggleMaximized) self.add_menu_action(self.window_menu, self.minimizeAct) self.add_menu_action(self.window_menu, self.maximizeAct) self.window_menu.addSeparator() prev_key = "Ctrl+Shift+Left" if sys.platform == 'darwin' else "Ctrl+PgUp" self.prev_tab_act = QtGui.QAction("Pre&vious Tab", self, shortcut=prev_key, statusTip="Select previous tab", triggered=self.prev_tab) self.add_menu_action(self.window_menu, self.prev_tab_act) next_key = "Ctrl+Shift+Right" if sys.platform == 'darwin' else "Ctrl+PgDown" self.next_tab_act = QtGui.QAction("Ne&xt Tab", self, shortcut=next_key, statusTip="Select next tab", triggered=self.next_tab) self.add_menu_action(self.window_menu, self.next_tab_act)
def init_qt_elements(self): # Create the widget. self.app = QtGui.QApplication([]) base_path = os.path.abspath(os.path.dirname(__file__)) icon_path = os.path.join(base_path, 'resources', 'icon', 'IPythonConsole.svg') self.app.icon = QtGui.QIcon(icon_path) QtGui.QApplication.setWindowIcon(self.app.icon) try: ip = self.config.KernelManager.ip except AttributeError: ip = LOCALHOST local_kernel = (not self.existing) or ip in LOCAL_IPS self.widget = self.widget_factory(config=self.config, local_kernel=local_kernel) self.init_colors(self.widget) self.widget._existing = self.existing self.widget._may_close = not self.existing self.widget._confirm_exit = self.confirm_exit self.widget.kernel_manager = self.kernel_manager self.window = MainWindow( self.app, confirm_exit=self.confirm_exit, new_frontend_factory=self.new_frontend_master, slave_frontend_factory=self.new_frontend_slave, ) self.window.log = self.log self.window.add_tab_with_frontend(self.widget) self.window.init_menu_bar() self.window.setWindowTitle('IPython')
def init_help_menu(self): # please keep the Help menu in Mac Os even if empty. It will # automatically contain a search field to search inside menus and # please keep it spelled in English, as long as Qt Doesn't support # a QAction.MenuRole like HelpMenuRole otherwise it will lose # this search field functionality self.help_menu = self.menuBar().addMenu("&Help") # Help Menu self.intro_active_frontend_action = QtGui.QAction( "&Intro to IPython", self, triggered=self.intro_active_frontend) self.add_menu_action(self.help_menu, self.intro_active_frontend_action) self.quickref_active_frontend_action = QtGui.QAction( "IPython &Cheat Sheet", self, triggered=self.quickref_active_frontend) self.add_menu_action(self.help_menu, self.quickref_active_frontend_action) self.guiref_active_frontend_action = QtGui.QAction( "&Qt Console", self, triggered=self.guiref_active_frontend) self.add_menu_action(self.help_menu, self.guiref_active_frontend_action) self.onlineHelpAct = QtGui.QAction("Open Online &Help", self, triggered=self._open_online_help) self.add_menu_action(self.help_menu, self.onlineHelpAct)
def paintEvent(self, event): """ Reimplemented to paint the background panel. """ painter = QtGui.QStylePainter(self) option = QtGui.QStyleOptionFrame() option.initFrom(self) painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option) painter.end() super(CallTipWidget, self).paintEvent(event)
def __init__(self, *args, **kw): super(FrontendWidget, self).__init__(*args, **kw) # FIXME: remove this when PySide min version is updated past 1.0.7 # forcefully disable calltips if PySide is < 1.0.7, because they crash if qt.QT_API == qt.QT_API_PYSIDE: import PySide if PySide.__version_info__ < (1, 0, 7): self.log.warn( "PySide %s < 1.0.7 detected, disabling calltips" % PySide.__version__) self.enable_calltips = False # FrontendWidget protected variables. self._bracket_matcher = BracketMatcher(self._control) self._call_tip_widget = CallTipWidget(self._control) self._completion_lexer = CompletionLexer(self.lexer) self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None) self._hidden = False self._highlighter = FrontendHighlighter(self, lexer=self.lexer) self._input_splitter = self._input_splitter_class() self._kernel_manager = None self._kernel_client = None self._request_info = {} self._request_info['execute'] = {} self._callback_dict = {} # Configure the ConsoleWidget. self.tab_width = 4 self._set_continuation_prompt('... ') # Configure the CallTipWidget. self._call_tip_widget.setFont(self.font) self.font_changed.connect(self._call_tip_widget.setFont) # Configure actions. action = self._copy_raw_action key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C action.setEnabled(False) action.setShortcut(QtGui.QKeySequence(key)) action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) action.triggered.connect(self.copy_raw) self.copy_available.connect(action.setEnabled) self.addAction(action) # Connect signal handlers. document = self._control.document() document.contentsChange.connect(self._document_contents_change) # Set flag for whether we are connected via localhost. self._local_kernel = kw.get('local_kernel', FrontendWidget._local_kernel) # Whether or not a clear_output call is pending new output. self._pending_clearoutput = False
def __init__(self, text_edit): """ Create a call tip manager that is attached to the specified Qt text edit widget. """ assert isinstance(text_edit, (QtGui.QTextEdit, QtGui.QPlainTextEdit)) super(BracketMatcher, self).__init__() # The format to apply to matching brackets. self.format = QtGui.QTextCharFormat() self.format.setBackground(QtGui.QColor('silver')) self._text_edit = text_edit text_edit.cursorPositionChanged.connect(self._cursor_position_changed)
def init_edit_menu(self): self.edit_menu = self.menuBar().addMenu("&Edit") self.undo_action = QtGui.QAction( "&Undo", self, shortcut=QtGui.QKeySequence.Undo, statusTip="Undo last action if possible", triggered=self.undo_active_frontend) self.add_menu_action(self.edit_menu, self.undo_action) self.redo_action = QtGui.QAction( "&Redo", self, shortcut=QtGui.QKeySequence.Redo, statusTip="Redo last action if possible", triggered=self.redo_active_frontend) self.add_menu_action(self.edit_menu, self.redo_action) self.edit_menu.addSeparator() self.cut_action = QtGui.QAction("&Cut", self, shortcut=QtGui.QKeySequence.Cut, triggered=self.cut_active_frontend) self.add_menu_action(self.edit_menu, self.cut_action, True) self.copy_action = QtGui.QAction("&Copy", self, shortcut=QtGui.QKeySequence.Copy, triggered=self.copy_active_frontend) self.add_menu_action(self.edit_menu, self.copy_action, True) self.copy_raw_action = QtGui.QAction( "Copy (&Raw Text)", self, shortcut="Ctrl+Shift+C", triggered=self.copy_raw_active_frontend) self.add_menu_action(self.edit_menu, self.copy_raw_action, True) self.paste_action = QtGui.QAction("&Paste", self, shortcut=QtGui.QKeySequence.Paste, triggered=self.paste_active_frontend) self.add_menu_action(self.edit_menu, self.paste_action, True) self.edit_menu.addSeparator() selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll) if selectall.matches("Ctrl+A") and sys.platform != 'darwin': # Only override the default if there is a collision. # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX. selectall = "Ctrl+Shift+A" self.select_all_action = QtGui.QAction( "Select &All", self, shortcut=selectall, triggered=self.select_all_active_frontend) self.add_menu_action(self.edit_menu, self.select_all_action, True)
def _get_color(self, color): """ Returns a QColor built from a Pygments color string. """ qcolor = QtGui.QColor() qcolor.setRgb(int(color[:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16)) return qcolor
def populate_all_magic_menu(self, display_data=None): """Clean "All Magics..." menu and repopulate it with `display_data` Parameters ---------- display_data : dict, dict of display_data for the magics dict of a MagicsManager. Expects json data, as the result of %lsmagic """ for k, v in self._magic_menu_dict.items(): v.clear() self.all_magic_menu.clear() if not display_data: return if display_data['status'] != 'ok': self.log.warn("%%lsmagic user-expression failed: %s" % display_data) return mdict = json.loads(display_data['data'].get('application/json', {})) for mtype in sorted(mdict): subdict = mdict[mtype] prefix = magic_escapes[mtype] for name in sorted(subdict): mclass = subdict[name] magic_menu = self._get_magic_menu(mclass) pmagic = prefix + name xaction = QtGui.QAction( pmagic, self, triggered=self._make_dynamic_magic(pmagic)) magic_menu.addAction(xaction) self.all_magic_menu.addAction(xaction)
def __init__(self, parent, lexer=None): super(PygmentsHighlighter, self).__init__(parent) self._document = QtGui.QTextDocument() self._formatter = HtmlFormatter(nowrap=True) self._lexer = lexer if lexer else PythonLexer() self.set_style('default')
def _insert_img(self, cursor, img, fmt, metadata=None): """ insert a raw image, jpg or png """ if metadata: width = metadata.get('width', None) height = metadata.get('height', None) else: width = height = None try: image = QtGui.QImage() image.loadFromData(img, fmt.upper()) if width and height: image = image.scaled( width, height, transformMode=QtCore.Qt.SmoothTransformation) elif width and not height: image = image.scaledToWidth( width, transformMode=QtCore.Qt.SmoothTransformation) elif height and not width: image = image.scaledToHeight( height, transformMode=QtCore.Qt.SmoothTransformation) except ValueError: self._insert_plain_text(cursor, 'Received invalid %s data.' % fmt) else: format = self._add_image(image) cursor.insertBlock() cursor.insertImage(format) cursor.insertBlock()
def populate_all_magic_menu(self, listofmagic=None): """Clean "All Magics..." menu and repopulate it with `listofmagic` Parameters ---------- listofmagic : string, repr() of a list of strings, send back by the kernel Notes ----- `listofmagic`is a repr() of list because it is fed with the result of a 'user_expression' """ for k, v in self._magic_menu_dict.items(): v.clear() self.all_magic_menu.clear() mlist = ast.literal_eval(listofmagic) for magic in mlist: cell = (magic['type'] == 'cell') name = magic['name'] mclass = magic['class'] if cell: prefix = '%%' else: prefix = '%' magic_menu = self._get_magic_menu(mclass) pmagic = '%s%s' % (prefix, name) xaction = QtGui.QAction(pmagic, self, triggered=self._make_dynamic_magic(pmagic)) magic_menu.addAction(xaction) self.all_magic_menu.addAction(xaction)
def _handle_telemetry_context_menu(self, pos): item = self.ui.telemetryTreeWidget.itemAt(pos) if item.childCount() > 0: return menu = QtGui.QMenu(self) left_action = menu.addAction('Plot Left') right_action = menu.addAction('Plot Right') menu.addSeparator() copy_name = menu.addAction('Copy Name') copy_value = menu.addAction('Copy Value') requested = menu.exec_(self.ui.telemetryTreeWidget.mapToGlobal(pos)) if requested == left_action or requested == right_action: name = _get_item_name(item) root = _get_item_root(item) record = self._telemetry_records[root] leaf = name.split('.', 1)[1] axis = 0 if requested == right_action: axis = 1 plot_item = self.ui.plotWidget.add_plot(name, record.get_signal(leaf), axis) self.ui.plotItemCombo.addItem(name, plot_item) elif requested == copy_name: QtGui.QApplication.clipboard().setText(item.text(0)) elif requested == copy_value: QtGui.QApplication.clipboard().setText(item.text(1)) else: # The user cancelled. pass
def populate_all_magic_menu(self, listofmagic=None): """Clean "All Magics..." menu and repopulate it with `listofmagic` Parameters ---------- listofmagic : string, repr() of a list of strings, send back by the kernel Notes ----- `listofmagic`is a repr() of list because it is fed with the result of a 'user_expression' """ alm_magic_menu = self.all_magic_menu alm_magic_menu.clear() # list of protected magic that don't like to be called without argument # append '?' to the end to print the docstring when called from the menu protected_magic = set( ["more", "less", "load_ext", "pycat", "loadpy", "save"]) magics = re.findall('\w+', listofmagic) for magic in magics: if magic in protected_magic: pmagic = '%s%s%s' % ('%', magic, '?') else: pmagic = '%s%s' % ('%', magic) xaction = QtGui.QAction(pmagic, self, triggered=self._make_dynamic_magic(pmagic)) alm_magic_menu.addAction(xaction)
def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1)
def setUpClass(cls): """ Create the application for the test case. """ cls._app = QtGui.QApplication.instance() if cls._app is None: cls._app = QtGui.QApplication([]) cls._app.setQuitOnLastWindowClosed(False)
def init_qt_elements(self): # Create the widget. base_path = os.path.abspath(os.path.dirname(__file__)) icon_path = os.path.join(base_path, 'resources', 'icon', 'IPythonConsole.svg') self.app.icon = QtGui.QIcon(icon_path) QtGui.QApplication.setWindowIcon(self.app.icon) ip = self.ip local_kernel = (not self.existing) or is_local_ip(ip) self.widget = self.widget_factory(config=self.config, local_kernel=local_kernel) self.init_colors(self.widget) self.widget._existing = self.existing self.widget._may_close = not self.existing self.widget._confirm_exit = self.confirm_exit self.widget.kernel_manager = self.kernel_manager self.widget.kernel_client = self.kernel_client self.window = MainWindow( self.app, confirm_exit=self.confirm_exit, new_frontend_factory=self.new_frontend_master, slave_frontend_factory=self.new_frontend_slave, ) self.window.log = self.log self.window.add_tab_with_frontend(self.widget) self.window.init_menu_bar() # Ignore on OSX, where there is always a menu bar if sys.platform != 'darwin' and self.hide_menubar: self.window.menuBar().setVisible(False) self.window.setWindowTitle('IPython')
def save_svg(string, parent=None): """ Prompts the user to save an SVG document to disk. Parameters: ----------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns: -------- The name of the file to which the document was saved, or None if the save was cancelled. """ if isinstance(string, unicode_type): string = string.encode('utf-8') dialog = QtGui.QFileDialog(parent, 'Save SVG Document') dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix('svg') dialog.setNameFilter('SVG document (*.svg)') if dialog.exec_(): filename = dialog.selectedFiles()[0] f = open(filename, 'wb') try: f.write(string) finally: f.close() return filename return None
def get_catalog(self): self.catalog_id = self.get_catalog_id(self.catalog_box.currentText()) _, self.datasets = self.wrap.catalogClient.get_datasets( self.catalog_id) dataset_layout = QtGui.QHBoxLayout() self.dataset_box = QtGui.QComboBox() for dataset in self.datasets: try: self.dataset_box.addItem(dataset['name']) except: pass self.dataset_box.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) dataset_button = QtGui.QPushButton("Choose Dataset") dataset_button.clicked.connect(self.get_dataset) dataset_layout.addWidget(self.dataset_box) dataset_layout.addWidget(dataset_button) self.layout.insertLayout(1, dataset_layout)
def get_dataset(self): self.dataset_id = self.get_dataset_id(self.dataset_box.currentText()) _, self.members = self.wrap.catalogClient.get_members( self.catalog_id, self.dataset_id) member_layout = QtGui.QHBoxLayout() self.member_box = QtGui.QComboBox() for member in self.members: try: self.member_box.addItem(member['data_uri']) except: pass self.member_box.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) member_button = QtGui.QPushButton("Choose Member") member_button.clicked.connect(self.get_member) member_layout.addWidget(self.member_box) member_layout.addWidget(member_button) self.layout.insertLayout(2, member_layout)
def init_magic_menu(self): self.magic_menu = self.menuBar().addMenu("&Magic") self.magic_menu_separator = self.magic_menu.addSeparator() self.all_magic_menu = self._get_magic_menu("AllMagics", menulabel="&All Magics...") # This action should usually not appear as it will be cleared when menu # is updated at first kernel response. Though, it is necessary when # connecting through X-forwarding, as in this case, the menu is not # auto updated, SO DO NOT DELETE. self.pop = QtGui.QAction("&Update All Magic Menu ", self, triggered=self.update_all_magic_menu) self.add_menu_action(self.all_magic_menu, self.pop) # we need to populate the 'Magic Menu' once the kernel has answer at # least once let's do it immediately, but it's assured to works self.pop.trigger() self.reset_action = QtGui.QAction( "&Reset", self, statusTip="Clear all variables from workspace", triggered=self.reset_magic_active_frontend) self.add_menu_action(self.magic_menu, self.reset_action) self.history_action = QtGui.QAction( "&History", self, statusTip="show command history", triggered=self.history_magic_active_frontend) self.add_menu_action(self.magic_menu, self.history_action) self.save_action = QtGui.QAction( "E&xport History ", self, statusTip="Export History as Python File", triggered=self.save_magic_active_frontend) self.add_menu_action(self.magic_menu, self.save_action) self.who_action = QtGui.QAction( "&Who", self, statusTip="List interactive variables", triggered=self.who_magic_active_frontend) self.add_menu_action(self.magic_menu, self.who_action) self.who_ls_action = QtGui.QAction( "Wh&o ls", self, statusTip="Return a list of interactive variables", triggered=self.who_ls_magic_active_frontend) self.add_menu_action(self.magic_menu, self.who_ls_action) self.whos_action = QtGui.QAction( "Who&s", self, statusTip="List interactive variables with details", triggered=self.whos_magic_active_frontend) self.add_menu_action(self.magic_menu, self.whos_action)
def _get_brush(self, color): """ Returns a brush for the color. """ result = self._brushes.get(color) if result is None: qcolor = self._get_color(color) result = QtGui.QBrush(qcolor) self._brushes[color] = result return result
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.history_s = 20.0 self.next_color = 0 self.paused = False self.figure = matplotlib.figure.Figure() self.canvas = FigureCanvas(self.figure) self.canvas.mpl_connect('key_press_event', self.handle_key_press) self.canvas.mpl_connect('key_release_event', self.handle_key_release) self.left_axis = self.figure.add_subplot(111) self.left_axis.grid() self.left_axis.fmt_xdata = lambda x: '%.3f' % x self.left_axis.legend_loc = LEFT_LEGEND_LOC self.right_axis = None def draw(): # NOTE jpieper: For some reason, on the first repaint # event, the height is negative, which throws spurious # errors. Paper over that here. l, b, w, h = self.figure.bbox.bounds if h < 0: return FigureCanvas.draw(self.canvas) self.canvas.repaint() self.canvas.draw = draw self.toolbar = backend_qt4agg.NavigationToolbar2QT(self.canvas, self) self.pause_action = QtGui.QAction(u'Pause', self) self.pause_action.setCheckable(True) self.pause_action.toggled.connect(self._handle_pause) self.toolbar.addAction(self.pause_action) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.toolbar, 0) layout.addWidget(self.canvas, 1) self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
def closeEvent(self, event): """ Forward the close event to every tabs contained by the windows """ if self.tab_widget.count() == 0: # no tabs, just close event.accept() return # Do Not loop on the widget count as it change while closing title = self.window().windowTitle() cancel = QtGui.QMessageBox.Cancel okay = QtGui.QMessageBox.Ok accept_role = QtGui.QMessageBox.AcceptRole if self.confirm_exit: if self.tab_widget.count() > 1: msg = "Close all tabs, stop all kernels, and Quit?" else: msg = "Close console, stop kernel, and Quit?" info = "Kernels not started here (e.g. notebooks) will be left alone." closeall = QtGui.QPushButton("&Quit", self) closeall.setShortcut('Q') box = QtGui.QMessageBox(QtGui.QMessageBox.Question, title, msg) box.setInformativeText(info) box.addButton(cancel) box.addButton(closeall, QtGui.QMessageBox.YesRole) box.setDefaultButton(closeall) box.setEscapeButton(cancel) pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(64,64))) box.setIconPixmap(pixmap) reply = box.exec_() else: reply = okay if reply == cancel: event.ignore() return if reply == okay or reply == accept_role: while self.tab_widget.count() >= 1: # prevent further confirmations: widget = self.active_frontend widget._confirm_exit = False self.close_tab(widget) event.accept()
def init_file_menu(self): self.file_menu = self.menuBar().addMenu("&File") self.new_kernel_tab_act = QtGui.QAction( "New Tab with &New kernel", self, shortcut="Ctrl+T", triggered=self.create_tab_with_new_frontend) self.add_menu_action(self.file_menu, self.new_kernel_tab_act) self.slave_kernel_tab_act = QtGui.QAction( "New Tab with Sa&me kernel", self, shortcut="Ctrl+Shift+T", triggered=self.create_tab_with_current_kernel) self.add_menu_action(self.file_menu, self.slave_kernel_tab_act) self.file_menu.addSeparator() self.close_action = QtGui.QAction("&Close Tab", self, shortcut=QtGui.QKeySequence.Close, triggered=self.close_active_frontend) self.add_menu_action(self.file_menu, self.close_action) self.export_action = QtGui.QAction( "&Save to HTML/XHTML", self, shortcut=QtGui.QKeySequence.Save, triggered=self.export_action_active_frontend) self.add_menu_action(self.file_menu, self.export_action, True) self.file_menu.addSeparator() printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print) if printkey.matches("Ctrl+P") and sys.platform != 'darwin': # Only override the default if there is a collision. # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX. printkey = "Ctrl+Shift+P" self.print_action = QtGui.QAction( "&Print", self, shortcut=printkey, triggered=self.print_action_active_frontend) self.add_menu_action(self.file_menu, self.print_action, True) if sys.platform != 'darwin': # OSX always has Quit in the Application menu, only add it # to the File menu elsewhere. self.file_menu.addSeparator() self.quit_action = QtGui.QAction( "&Quit", self, shortcut=QtGui.QKeySequence.Quit, triggered=self.close, ) self.add_menu_action(self.file_menu, self.quit_action)