def main(): """Start kernel manager, create window, run app event loop, auto execute some code in user namespace. Adapted from IPython example in: docs/examples/frontend/inprocess_qtconsole.py""" app = guisupport.get_app_qt4() if INPROCESS: from IPython.kernel.inprocess.ipkernel import InProcessKernel from IPython.frontend.qt.inprocess_kernelmanager import QtInProcessKernelManager kernel = InProcessKernel(gui='qt4') km = QtInProcessKernelManager(kernel=kernel) kernel.frontends.append(km) else: from IPython.frontend.qt.kernelmanager import QtKernelManager km = QtKernelManager() km.start_kernel() km.start_channels() neuropywindow = NeuropyWindow() ipw = neuropywindow.ipw config_ipw(ipw) ipw.exit_requested.connect(app.quit) ipw.kernel_manager = km neuropywindow.show() # execute some code directly, note the output appears at the system command line: #kernel.shell.run_cell('print "x=%r, y=%r, z=%r" % (x,y,z)') # execute some code through the frontend (once the event loop is # running). The output appears in the ipw: do_later(ipw.execute_file, 'startup.py', hidden=True) # import division in startup.py doesn't seem to work, execute directly: do_later(ipw.execute, "from __future__ import division", hidden=True) do_later(ipw.execute_file, 'globals.py', hidden=True) guisupport.start_event_loop_qt4(app)
def show_ipython_console(): # from https://github.com/ipython/ipython/blob/1.x/examples/inprocess/embedded_qtconsole.py # this might be able to be a dockable panel at some point in the future. # it should also only allow one window open at a time - I think it steals stdout at start # and opening a new window stops output working on the old one! app = guisupport.get_app_qt4() # Create an in-process kernel # >>> print_process_id() # will print the same process ID as the main process kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() app.exit() control = RichIPythonWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(stop) control.show() guisupport.start_event_loop_qt4(app)
def main(): # Print the ID of the main process print_process_id() app = guisupport.get_app_qt4() # Create an in-process kernel # >>> print_process_id() # will print the same process ID as the main process kernel_manager = QtAsyncInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel.shell.push({'foo': 43, 'print_process_id': print_process_id}) kernel_client = kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() app.exit() control = RichIPythonWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(stop) control.show() guisupport.start_event_loop_qt4(app)
def show(model): """Take an instance of tardis model and display it. If IPython functions were successfully imported then QApplication instance is created using get_app_qt4. This will only create the app instance if it doesn't already exists. Otherwise it is explicitly started. Then the mainwindow is created, the model is attached to it and its show method is called. Finally the eventloop is started using IPython functions (which start them consistently) if they were imported. Otherwise it is started explicitly. """ if importFailed: app = QtGui.QApplication([]) else: app = get_app_qt4() tablemodel = SimpleTableModel win = Tardis(tablemodel) win.show_model(model) if importFailed: app.exec_() else: start_event_loop_qt4(app) #If the IPython console is being used, this will evaluate to true. #In that case the window created will be garbage collected unless a #reference to it is maintained after this function exits. So the win is #returned. if is_event_loop_running_qt4(app): return win
def show_ipython_console(): # from https://github.com/ipython/ipython/blob/1.x/examples/inprocess/embedded_qtconsole.py # this might be able to be a dockable panel at some point in the future. # it should also only allow one window open at a time - I think it steals stdout at start # and opening a new window stops output working on the old one! app = guisupport.get_app_qt4() # Create an in-process kernel # >>> print_process_id() # will print the same process ID as the main process kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel_client = kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() app.exit() control = RichIPythonWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(stop) control.show() guisupport.start_event_loop_qt4(app)
def main(): """Start kernel manager and client, create window, run app event loop""" app = guisupport.get_app_qt4() if INPROCESS: from qtconsole.inprocess import QtInProcessKernelManager km = QtInProcessKernelManager() else: from qtconsole.manager import QtKernelManager km = QtKernelManager() km.start_kernel() km.kernel.gui = 'qt4' kc = km.client() kc.start_channels() widget = RichJupyterWidget() widget.kernel_manager = km widget.kernel_client = kc if CLEANSHUTDOWN: # slow exit on CTRL+D def stop(): kc.stop_channels() km.shutdown_kernel() app.exit() widget.exit_requested.connect(stop) else: # fast exit on CTRL+D widget.exit_requested.connect(app.quit) widget.show() guisupport.start_event_loop_qt4(app)
def create_window(window_class, **kwargs): """Create a QT window in Python, or interactively in IPython with QT GUI event loop integration. """ global app app = get_app_qt4(sys.argv) app.references = set() net = None fname = None if len(sys.argv) > 1: fname = sys.argv[1] if os.path.exists(fname): net = read_pickle(fname) else: QMessageBox.critical(None, "Error opening file %s", fname, QMessageBox.Ok, QMessageBox.NoButton) window = window_class(net, fname) app.references.add(window) window.show() start_event_loop_qt4(app) return window
def main(): # Print the ID of the main process print_process_id() init_asyncio_patch() app = guisupport.get_app_qt4() # Create an in-process kernel # >>> print_process_id() # will print the same process ID as the main process kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' kernel.shell.push({'foo': 43, 'print_process_id': print_process_id}) kernel_client = kernel_manager.client() kernel_client.start_channels() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() app.exit() control = RichIPythonWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(stop) control.show() guisupport.start_event_loop_qt4(app)
def create_window(window_class, **kwargs): """Create a QT window in Python, or interactively in IPython with QT GUI event loop integration. """ global app app = get_app_qt4(sys.argv) app.references = set() net = None fname = None if len(sys.argv) > 1: fname = sys.argv[1] if os.path.exists(fname): net = read_pickle(fname) else: QMessageBox.critical( None, "Error opening file %s", fname, QMessageBox.Ok, QMessageBox.NoButton) window = window_class(net, fname) app.references.add(window) window.show() start_event_loop_qt4(app) return window
def start_qt_event_loop(qApp): """ Starts the eventloop if it's not yet running. If the IPython event loop is active (and set to Qt) this function does nothing. The IPython event loop will process Qt events as well so the user can continue to use the command prompt together with the ObjectBrower. Unfortunately this behaviour is broken again in IPython 5, so there we fall back on the non-interactive event loop. """ if in_ipython(): from IPython import version_info logger.debug("IPython detected. Version info: {}".format(version_info)) if version_info[0] < 4: logger.debug("Event loop integration not supported for IPython < 4") elif version_info[0] == 5 and version_info[1] <= 1: # The is_event_loop_running_qt4 function is broken in IPython 5.0 and 5.1. # https://github.com/ipython/ipython/issues/9974 logger.debug("Event loop integration does not work in IPython 5.0 and 5.1") else: try: from IPython.lib.guisupport import is_event_loop_running_qt4, start_event_loop_qt4 if is_event_loop_running_qt4(qApp): logger.info("IPython event loop already running. GUI integration possible.") else: # No gui integration logger.info("Starting (non-interactive) IPython event loop") start_event_loop_qt4(qApp) # exit code always 0 return except Exception as ex: logger.warning("Unable to start IPython Qt event loop: {}".format(ex)) logger.warning("Falling back on non-interactive event loop: {}".format(ex)) logger.info("Starting (non-interactive) event loop") return qApp.exec_()
def show(model): """Take an instance of tardis model and display it. If IPython functions were successfully imported then QApplication instance is created using get_app_qt4. This will only create the app instance if it doesn't already exists. Otherwise it is explicitly started. Then the mainwindow is created, the model is attached to it and its show method is called. Finally the eventloop is started using IPython functions (which start them consistently) if they were imported. Otherwise it is started explicitly. """ if importFailed: app = QtGui.QApplication([]) else: app = get_app_qt4() tablemodel = SimpleTableModel win = Tardis(tablemodel) win.show_model(model) if importFailed: app.exec_() else: start_event_loop_qt4(app) #If the IPython console is being used, this will evaluate to true. #In that case the window created will be garbage collected unless a #reference to it is maintained after this function exits. So the win is #returned. if is_event_loop_running_qt4(app): return win
def main(): """Start kernel manager and client, create window, run app event loop""" app = guisupport.get_app_qt4() if INPROCESS: from IPython.qt.inprocess import QtInProcessKernelManager km = QtInProcessKernelManager() else: from IPython.qt.manager import QtKernelManager km = QtKernelManager() km.start_kernel() km.kernel.gui = 'qt4' kc = km.client() kc.start_channels() widget = RichIPythonWidget() widget.kernel_manager = km widget.kernel_client = kc if CLEANSHUTDOWN: # slow exit on CTRL+D def stop(): kc.stop_channels() km.shutdown_kernel() app.exit() widget.exit_requested.connect(stop) else: # fast exit on CTRL+D widget.exit_requested.connect(app.quit) widget.show() guisupport.start_event_loop_qt4(app)
def start(self): # draw the window self.window.show() self.window.raise_() # Start the application main loop. guisupport.start_event_loop_qt4(self.app)
def qtapp_loop_nonblocking(qwin=None, **kwargs): global QAPP #from IPython.lib.inputhook import enable_qt4 from IPython.lib.guisupport import start_event_loop_qt4 if not QUIET: print('[guitool] Starting ipython qt4 hook') #enable_qt4() start_event_loop_qt4(QAPP)
def start(self): # draw the window self.window.show() self.window.raise_() # Start the application main loop. guisupport.start_event_loop_qt4(self.app)
def run(): # app = QtGui.QApplication.instance() # checks if QApplication already exists # if not app: # create QApplication if it doesnt exist # app = QtGui.QApplication(sys.argv) app = guisupport.get_app_qt4() global browser # otherwise window appears and immediately disappears browser = PlotBrowser() browser.show() guisupport.start_event_loop_qt4(app)
def qtapp_loop_nonblocking(qwin=None, **kwargs): global QAPP # from IPython.lib.inputhook import enable_qt4 from IPython.lib.guisupport import start_event_loop_qt4 if not QUIET: print("[guitool] Starting ipython qt4 hook") # enable_qt4() start_event_loop_qt4(QAPP)
def run(): # app = QtGui.QApplication.instance() # checks if QApplication already exists # if not app: # create QApplication if it doesnt exist # app = QtGui.QApplication(sys.argv) app = guisupport.get_app_qt4() global browser # otherwise window appears and immediately disappears browser = PlotBrowser() browser.show() guisupport.start_event_loop_qt4(app)
def run_in_ipython(app): """ Attempts to run the QApplication in the IPython main loop, which requires the command "%gui qt" to be run prior to the script execution. On failure the Qt main loop is initialized instead """ try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: app.exec_()
def run_in_ipython(app): """ Attempts to run the QApplication in the IPython main loop, which requires the command "%gui qt" to be run prior to the script execution. On failure the Qt main loop is initialized instead """ try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: app.exec_()
def start_event_loop(): from IPython.lib.guisupport import start_event_loop_qt4, is_event_loop_running_qt4 from pyface.qt import QtCore if not is_event_loop_running_qt4(): print('qt4 event loop not running') print( 'starting event loop via IPython.lib.guisupport.start_event_loop_qt4' ) start_event_loop_qt4(QtCore.QCoreApplication.instance()) else: print('running qt4 event loop detected')
def loop_qt4(kernel): """Start a kernel with PyQt4 event loop integration.""" from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 kernel.app = get_app_qt4([" "]) kernel.app.setQuitOnLastWindowClosed(False) for s in kernel.shell_streams: _notify_stream_qt(kernel, s) start_event_loop_qt4(kernel.app)
def exec_core_event_loop(app): # This works but does not allow IPython injection print('[*guitools] running core application loop.') try: from IPython.lib.inputhook import enable_qt4 enable_qt4() from IPython.lib.guisupport import start_event_loop_qt4 print('Starting ipython qt4 hook') start_event_loop_qt4(app) except ImportError: pass app.exec_()
def loop_qt4(kernel): """Start a kernel with PyQt4 event loop integration.""" from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 kernel.app = get_app_qt4([" "]) kernel.app.setQuitOnLastWindowClosed(False) for s in kernel.shell_streams: _notify_stream_qt(kernel, s) start_event_loop_qt4(kernel.app)
def loop_qt4(kernel): """Start a kernel with PyQt4 event loop integration.""" from IPython.external.qt_for_kernel import QtCore from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 kernel.app = get_app_qt4([" "]) kernel.app.setQuitOnLastWindowClosed(False) kernel.timer = QtCore.QTimer() kernel.timer.timeout.connect(kernel.do_one_iteration) # Units for the timer are in milliseconds kernel.timer.start(1000*kernel._poll_interval) start_event_loop_qt4(kernel.app)
def start(self): """Start a kernel with QtPy4 event loop integration.""" from PyQt4 import QtCore from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 self.app = get_app_qt4([" "]) self.app.setQuitOnLastWindowClosed(False) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.do_one_iteration) # Units for the timer are in milliseconds self.timer.start(1000*self._poll_interval) start_event_loop_qt4(self.app)
def loop_qt4(kernel): """Start a kernel with PyQt4 event loop integration.""" from IPython.external.qt_for_kernel import QtCore from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 kernel.app = get_app_qt4([" "]) kernel.app.setQuitOnLastWindowClosed(False) kernel.timer = QtCore.QTimer() kernel.timer.timeout.connect(kernel.do_one_iteration) # Units for the timer are in milliseconds kernel.timer.start(1000 * kernel._poll_interval) start_event_loop_qt4(kernel.app)
def start(self): """Start a kernel with QtPy4 event loop integration.""" from PyQt4 import QtCore from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 self.app = get_app_qt4([" "]) self.app.setQuitOnLastWindowClosed(False) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.do_one_iteration) # Units for the timer are in milliseconds self.timer.start(1000 * self._poll_interval) start_event_loop_qt4(self.app)
def execute(args): app = guisupport.get_app_qt4(sys.argv) app.setApplicationName('HEXRD') # configure logging if args.debug: log_level = logging.DEBUG add_handler(log_level) else: log_level = logging.CRITICAL if args.quiet else logging.INFO ctlr = MainController(log_level, args.config) guisupport.start_event_loop_qt4(app)
def main(): """Create a QT window in Python, or interactively in IPython with QT GUI event loop integration. """ print_process_id() app = guisupport.get_app_qt4() app.references = set() window = GUI() app.references.add(window) window.show() guisupport.start_event_loop_qt4(app)
def execute(args): app = guisupport.get_app_qt4(sys.argv) app.setApplicationName('HEXRD') # configure logging if args.debug: log_level = logging.DEBUG add_handler(log_level) else: log_level = logging.CRITICAL if args.quiet else logging.INFO ctlr = MainController(log_level, args.config) guisupport.start_event_loop_qt4(app)
def run(self): if self.run_in_jupyter: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) return #if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): if not is_interactive(): if self.ipkernel is not None: self.ipkernel.user_module, self.ipkernel.user_ns = extract_module_locals( 1) self.ipkernel.shell.set_completer_frame() self.ipkernel.start() else: QtGui.QApplication.instance().exec_()
def main(): # Print the ID of the main process print_process_id() app = guisupport.get_app_qt4() control = terminal_widget(testing=123) def stop(): control.kernel_client.stop_channels() control.kernel_manager.shutdown_kernel() app.exit() control.exit_requested.connect(stop) control.show() guisupport.start_event_loop_qt4(app)
def main(): # Print the ID of the main process print_process_id() app = guisupport.get_app_qt4() control = terminal_widget(testing=123) def stop(): control.kernel_client.stop_channels() control.kernel_manager.shutdown_kernel() app.exit() control.exit_requested.connect(stop) control.show() guisupport.start_event_loop_qt4(app)
def browse(*args, **kwargs): """ Opens and executes an ObjectBrowser window. If the env variable QT_API is set to 'pyside' and '%gui qt' run in IPython, this function will not block the session. """ app = get_qapplication_instance() _object_browse = create_object_browser(*args, **kwargs) app.references = set() app.references.add(_object_browse) try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: exit_code = app.exec_() logger.info("Object browser(s) done...") else: exit_code = 0 return exit_code
def start_qt_event_loop(qApp): """ Starts the eventloop if it's not yet running. If the IPython event loop is active (and set to Qt) this function does nothing. The IPython event loop will process Qt events as well so the user can continue to use the command prompt together with the ObjectBrower. Unfortunately this behaviour is broken again in IPython 5, so there we fall back on the non-interactive event loop. """ if in_ipython(): from IPython import version_info logger.debug("IPython detected. Version info: {}".format(version_info)) if version_info[0] < 4: logger.debug( "Event loop integration not supported for IPython < 4") elif version_info[0] == 5 and version_info[1] <= 1: # The is_event_loop_running_qt4 function is broken in IPython 5.0 and 5.1. # https://github.com/ipython/ipython/issues/9974 logger.debug( "Event loop integration does not work in IPython 5.0 and 5.1") else: try: from IPython.lib.guisupport import is_event_loop_running_qt4, start_event_loop_qt4 if is_event_loop_running_qt4(qApp): logger.info( "IPython event loop already running. GUI integration possible." ) else: # No gui integration logger.info( "Starting (non-interactive) IPython event loop") start_event_loop_qt4(qApp) # exit code always 0 return except Exception as ex: logger.warning( "Unable to start IPython Qt event loop: {}".format(ex)) logger.warning( "Falling back on non-interactive event loop: {}".format( ex)) logger.info("Starting (non-interactive) event loop") return qApp.exec_()
def __init__(self, parent=None): # assumes that qt has already been initialized by starting IPython with the flag "--pylab=qt" app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([]) try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: app.exec_() super(ModelViewer, self).__init__(parent) self.model = None self.setGeometry(20, 35, 1200, 500) self.setWindowTitle('Shells Viewer') self.tablemodel = MyTableModel(["t_rad", "Ws"]) self.tableview = QtGui.QTableView() self.graph = MatplotlibWidget(self, 'model') self.spectrum = MatplotlibWidget(self) self.spectrum_button = QtGui.QToolButton(self) self.layout = QtGui.QHBoxLayout() self.sublayout = QtGui.QVBoxLayout()
def plot_pulse_seqs(AWGWFs): ''' Helper function to plot direct awg waveforms. Expects a dictionary keyed on AWG's. ''' #Look to see if iPython's event loop is running app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication(sys.argv) plotterWindow = PulseSeqPlotWindow(AWGWFs) plotterWindow.show() try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: sys.exit(app.exec_()) #Need to a keep a reference to the window alive. return plotterWindow
def __init__(self, parent=None): # assumes that qt has already been initialized by starting IPython with the flag "--pylab=qt" app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([]) try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: app.exec_() super(ModelViewer, self).__init__(parent) self.model = None self.setGeometry(20, 35, 1200, 500) self.setWindowTitle('Shells Viewer') self.tablemodel = MyTableModel(["t_rad", "Ws"]) self.tableview = QtGui.QTableView() self.graph = MatplotlibWidget(self, 'model') self.spectrum = MatplotlibWidget(self) self.spectrum_button = QtGui.QToolButton(self) self.layout = QtGui.QHBoxLayout() self.sublayout = QtGui.QVBoxLayout()
def plot_pulse_seqs(AWGWFs): ''' Helper function to plot direct awg waveforms. Expects a dictionary keyed on AWG's. ''' #Look to see if iPython's event loop is running app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication(sys.argv) plotterWindow = PulseSeqPlotWindow(AWGWFs) plotterWindow.show() try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: sys.exit(app.exec_()) #Need to a keep a reference to the window alive. return plotterWindow
def main(argv=None): if argv is None: argv = [] print('jupyter.amain; argv was None -> %s' % argv) app_created = False app = QCoreApplication.instance() if app is None: app = QApplication(sys.argv) app_created = True QApplication.setOrganizationName("pyNastran") QApplication.setOrganizationDomain(pyNastran.__website__) QApplication.setApplicationName("pyNastran") QApplication.setApplicationVersion(pyNastran.__version__) inputs = get_inputs(argv) window = MainWindow(inputs) try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: app.exec_()
def main(): """Start kernel manager and client, create window, run app event loop, auto execute some code in user namespace. A minimalist example is shown in qt_ip_test.py. This is gleaned from ipython.examples.inprocess.embedded_qtconsole and ipython.IPython.qt.console.qtconsoleapp.new_frontend_master()""" app = guisupport.get_app_qt4() if INPROCESS: from IPython.qt.inprocess import QtInProcessKernelManager km = QtInProcessKernelManager() else: from IPython.qt.manager import QtKernelManager km = QtKernelManager() km.start_kernel() km.kernel.gui = 'qt4' kc = km.client() kc.start_channels() neuropywindow = NeuropyWindow() ipw = neuropywindow.ipw config_ipw(ipw) ipw.exit_requested.connect(app.quit) ipw.kernel_manager = km ipw.kernel_client = kc neuropywindow.show() # execute some code directly, note the output appears at the system command line: #kernel.shell.run_cell('print "x=%r, y=%r, z=%r" % (x,y,z)') # execute some code through the frontend (once the event loop is running). # The output appears in the ipw. __future__ import in startup.py doesn't seem to work, # execute directly: do_later(ipw.execute, "from __future__ import division", hidden=True) do_later(ipw.execute, "from __future__ import print_function", hidden=True) do_later(ipw.execute_file, 'startup.py', hidden=True) do_later(ipw.execute_file, 'globals.py', hidden=True) guisupport.start_event_loop_qt4(app)
def main(): """Start kernel manager and client, create window, run app event loop, auto execute some code in user namespace. A minimalist example is shown in qt_ip_test.py. NOTE: Make sure that the Qt v2 API is being used by IPython by running `export QT_API=pyqt` at the command line before running neuropy, or by adding it to `.bashrc`""" app = guisupport.get_app_qt4() if INPROCESS: from qtconsole.inprocess import QtInProcessKernelManager km = QtInProcessKernelManager() else: from qtconsole.manager import QtKernelManager km = QtKernelManager() km.start_kernel() km.kernel.gui = 'qt4' kc = km.client() kc.start_channels() nw = NeuropyWindow() ipw = nw.ipw config_ipw(ipw) ipw.kernel_manager = km ipw.kernel_client = kc ipw.exit_requested.connect(nw.stop) nw.show() # execute some code directly, note the output appears at the system command line: #kernel.shell.run_cell('print "x=%r, y=%r, z=%r" % (x,y,z)') # execute some code through the frontend (once the event loop is running). # The output appears in the IPythonWidget (ipw). do_later(ipw.execute, 'execfile(%r)' % 'startup.py', hidden=True) do_later(ipw.execute, 'execfile(%r)' % 'globals.py', hidden=True) guisupport.start_event_loop_qt4(app)
def main(): app = guisupport.get_app_qt4() # Create a kernel. # # Setting the GUI is not necessary for the normal operation of the kernel, # but it is used for IPython GUI's integration, particularly in pylab. By # default, the inline backend is used, which is safe under all toolkits. # # WARNING: Under no circumstances should another GUI toolkit, like wx, be # used when running a Qt application. This will lead to unexpected behavior, # including segfaults. kernel = InProcessKernel(gui='qt4') # Populate the kernel's namespace. kernel.shell.push({'x': 0, 'y': 1, 'z': 2}) # Create a kernel manager for the frontend and register it with the kernel. km = QtInProcessKernelManager(kernel=kernel) km.start_channels() kernel.frontends.append(km) # Create the Qt console frontend. control = RichIPythonWidget() control.exit_requested.connect(app.quit) control.kernel_manager = km control.show() # Execute some code directly. Note where the output appears. kernel.shell.run_cell('print "x=%r, y=%r, z=%r" % (x,y,z)') # Execute some code through the frontend (once the event loop is # running). Again, note where the output appears. do_later(control.execute, '%who') guisupport.start_event_loop_qt4(app)
def __init__(self, parent=None): # assumes that qt has already been initialized by starting IPython with the flag "--pylab=qt" app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([]) try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: app.exec_() super(ModelViewer, self).__init__(parent) self.model = None self.shell_info = {} self.line_info = [] self.setGeometry(20, 35, 1250, 500) self.setWindowTitle('Shells Viewer') self.tablemodel = SimpleTableModel([['Shell: '], ["Rad. temp", "Ws"]], (1, 0)) self.tableview = QtGui.QTableView() self.graph = MatplotlibWidget(self, 'model') self.graph_label = QtGui.QLabel('Select Property:') self.graph_button = QtGui.QToolButton() self.spectrum = MatplotlibWidget(self) self.spectrum_label = QtGui.QLabel('Select Spectrum:') self.spectrum_button = QtGui.QToolButton() self.spectrum_span_button = QtGui.QPushButton('Show Wavelength Range') self.spectrum_line_info_button = QtGui.QPushButton('Show Line Info') self.layout = QtGui.QHBoxLayout() self.graph_sublayout = QtGui.QVBoxLayout() self.graph_subsublayout = QtGui.QHBoxLayout() self.spectrum_sublayout = QtGui.QVBoxLayout() self.spectrum_subsublayout = QtGui.QHBoxLayout() self.tableview.setMinimumWidth(200) self.tableview.connect(self.tableview.verticalHeader(), QtCore.SIGNAL('sectionClicked(int)'), self.graph.highlight_shell) self.tableview.connect(self.tableview.verticalHeader(), QtCore.SIGNAL('sectionDoubleClicked(int)'), self.on_header_double_clicked) self.graph_button.setText('Rad. temp') self.spectrum_button.setText('spec_flux_angstrom') self.graph_button.setPopupMode(QtGui.QToolButton.MenuButtonPopup) self.spectrum_button.setPopupMode(QtGui.QToolButton.MenuButtonPopup) self.graph_button.setMenu(QtGui.QMenu(self.graph_button)) self.spectrum_button.setMenu(QtGui.QMenu(self.spectrum_button)) self.graph_button.menu().addAction('Rad. temp').triggered.connect(self.change_graph_to_t_rads) self.graph_button.menu().addAction('Ws').triggered.connect(self.change_graph_to_ws) self.spectrum_button.menu().addAction('spec_flux_angstrom').triggered.connect(self.change_spectrum_to_spec_flux_angstrom) self.spectrum_button.menu().addAction('spec_virtual_flux_angstrom').triggered.connect(self.change_spectrum_to_spec_virtual_flux_angstrom) self.spectrum_span_button.clicked.connect(self.spectrum.show_span) self.spectrum_line_info_button.clicked.connect(self.spectrum.show_line_info) self.layout.addWidget(self.tableview) self.graph_subsublayout.addWidget(self.graph_label) self.graph_subsublayout.addWidget(self.graph_button) self.graph_sublayout.addLayout(self.graph_subsublayout) self.graph_sublayout.addWidget(self.graph) self.layout.addLayout(self.graph_sublayout) self.spectrum_subsublayout.addWidget(self.spectrum_span_button) self.spectrum_subsublayout.addWidget(self.spectrum_label) self.spectrum_subsublayout.addWidget(self.spectrum_button) self.spectrum_sublayout.addLayout(self.spectrum_subsublayout) self.spectrum_sublayout.addWidget(self.spectrum_line_info_button) self.spectrum_sublayout.addWidget(self.spectrum) self.spectrum_sublayout.addWidget(self.spectrum.toolbar) self.layout.addLayout(self.spectrum_sublayout) self.spectrum_line_info_button.hide() self.setLayout(self.layout)
def __init__(self, parent=None): # assumes that qt has already been initialized by starting IPython with the flag "--pylab=qt" app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([]) try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: app.exec_() super(ModelViewer, self).__init__(parent) self.model = None self.shell_info = {} self.line_info = [] self.setGeometry(20, 35, 1250, 500) self.setWindowTitle('Shells Viewer') self.tablemodel = SimpleTableModel([['Shell: '], ["t_rad", "Ws"]], (1, 0)) self.tableview = QtGui.QTableView() self.graph = MatplotlibWidget(self, 'model') self.graph_label = QtGui.QLabel('Select Property:') self.graph_button = QtGui.QToolButton() self.spectrum = MatplotlibWidget(self) self.spectrum_label = QtGui.QLabel('Select Spectrum:') self.spectrum_button = QtGui.QToolButton() self.spectrum_span_button = QtGui.QPushButton('Show Wavelength Range') self.spectrum_line_info_button = QtGui.QPushButton('Show Line Info') self.layout = QtGui.QHBoxLayout() self.graph_sublayout = QtGui.QVBoxLayout() self.graph_subsublayout = QtGui.QHBoxLayout() self.spectrum_sublayout = QtGui.QVBoxLayout() self.spectrum_subsublayout = QtGui.QHBoxLayout() self.tableview.setMinimumWidth(200) self.tableview.connect(self.tableview.verticalHeader(), QtCore.SIGNAL('sectionClicked(int)'), self.graph.highlight_shell) self.tableview.connect(self.tableview.verticalHeader(), QtCore.SIGNAL('sectionDoubleClicked(int)'), self.on_header_double_clicked) self.graph_button.setText('t_rads') self.spectrum_button.setText('spec_flux_angstrom') self.graph_button.setPopupMode(QtGui.QToolButton.MenuButtonPopup) self.spectrum_button.setPopupMode(QtGui.QToolButton.MenuButtonPopup) self.graph_button.setMenu(QtGui.QMenu(self.graph_button)) self.spectrum_button.setMenu(QtGui.QMenu(self.spectrum_button)) self.graph_button.menu().addAction('t_rads').triggered.connect(self.change_graph_to_t_rads) self.graph_button.menu().addAction('Ws').triggered.connect(self.change_graph_to_ws) self.spectrum_button.menu().addAction('spec_flux_angstrom').triggered.connect(self.change_spectrum_to_spec_flux_angstrom) self.spectrum_button.menu().addAction('spec_virtual_flux_angstrom').triggered.connect(self.change_spectrum_to_spec_virtual_flux_angstrom) self.spectrum_span_button.clicked.connect(self.spectrum.show_span) self.spectrum_line_info_button.clicked.connect(self.spectrum.show_line_info) self.layout.addWidget(self.tableview) self.graph_subsublayout.addWidget(self.graph_label) self.graph_subsublayout.addWidget(self.graph_button) self.graph_sublayout.addLayout(self.graph_subsublayout) self.graph_sublayout.addWidget(self.graph) self.layout.addLayout(self.graph_sublayout) self.spectrum_subsublayout.addWidget(self.spectrum_span_button) self.spectrum_subsublayout.addWidget(self.spectrum_label) self.spectrum_subsublayout.addWidget(self.spectrum_button) self.spectrum_sublayout.addLayout(self.spectrum_subsublayout) self.spectrum_sublayout.addWidget(self.spectrum_line_info_button) self.spectrum_sublayout.addWidget(self.spectrum) self.spectrum_sublayout.addWidget(self.spectrum.toolbar) self.layout.addLayout(self.spectrum_sublayout) self.spectrum_line_info_button.hide() self.setLayout(self.layout)
def console(client, args): local = { 'client': client, 'auth': client.auth, 'reset': client.reset, 'config': client.config, 'execute': client.execute, } if args['scriptName']: ############################################################# # EXECUTE FILE # ############################################################# sys.argv = [] sys.argv.append(args['scriptName']) sys.argv.extend(args['scriptArgs']) try: f = open(sys.argv[0]) source_code = f.read() f.close() except IOError as e: raise pyAMI.exception.Error(e) compiled_code = compile(source_code, sys.argv[0], 'exec') safe_exec(compiled_code, globals(), local) ############################################################# else: ############################################################# # RUN CONSOLE # ############################################################# sys.argv = [sys.argv[0]] ############################################################# banner = pyAMI.config.banner if args['nosplash'] == False else '' ############################################################# if args['gIPython']: ##################################################### # IPYTHON GRAPHICAL MODE # ##################################################### try: from IPython.qt.console.rich_ipython_widget import RichIPythonWidget from IPython.qt.inprocess import QtInProcessKernelManager from IPython.lib import guisupport except ImportError as e: raise pyAMI.exception.Error('module `IPython` not properly installed: %s' % e) ################################ # HACK IPYTHON BANNER # ################################ RichIPythonWidget._banner_default = lambda self: banner ################################ # KERNEL_MANAGER # ################################ kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() ################################ # KERNEL_CLIENT # ################################ kernel_client = kernel_manager.client() kernel_client.start_channels() ################################ # PYAMI # ################################ kernel_manager.kernel.shell.push(local) ################################ # APPLICATION # ################################ a = guisupport.get_app_qt4() def stop(): kernel_client.stop_channels() kernel_manager.shutdown_kernel() a.exit() control = RichIPythonWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(stop) control.show() guisupport.start_event_loop_qt4(a) ##################################################### elif args['cIPython']: ##################################################### # IPYTHON CONSOLE MODE # ##################################################### try: from IPython.terminal.embed import InteractiveShellEmbed except ImportError as e: raise pyAMI.exception.Error('module `IPython` not properly installed: %s' % e) ################################ # SHELL # ################################ shell = InteractiveShellEmbed(banner1 = banner, banner2 = None) shell(local_ns = local) ##################################################### else: ##################################################### # DEFAULT MODE # ##################################################### code.interact(banner = banner, local = local) ##################################################### return 0
from amoco.ui.render import Formats,conf from amoco.logger import Log logger = Log(__name__) logger.debug("loading module") #from . import rc_icons try: # integrate Qt mainloop into IPython console: # (the name qt4 here is a relic of the API but what happens # really is not restricted to Qt4...) from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 app = get_app_qt4() start_event_loop_qt4(app) except ImportError: app = QApplication.instance() or QApplication([]) app.setApplicationName("amoco-qt") # set default styleSheet: current_path = path.abspath(path.dirname(__file__)) filename = path.join(current_path, 'style.qss') filename = conf.UI.qstylesheet or filename if filename.startswith(":"): if filename[1:]=="qdarkstyle": try: import qdarkstyle app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyside2')) except: pass
'y': { 'z': 3, 'y': 9 } } # nested items my_namespace.c = { 'y': EmptyClass(), 5: 'q', (4, 5): 't' } # different keys for dict my_namespace.c['y'].z = [1, 2, 3] my_namespace.c['y'].y = 4 my_namespace.c['y'].x = my_namespace.c # circular reference my_namespace.d = np.matrix(b'[11,12,13;14,15,16;17,18,19]') my_namespace.e = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) my_namespace.s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) my_namespace.df = pd.DataFrame({ 'one': my_namespace.s, 'two': my_namespace.s }) my_namespace.n = 8 my_namespace.o = bytearray(b'hello') app = guisupport.get_app_qt4() # app = QtGui.QApplication(sys.argv) form = ObjectExplorer() form.show() guisupport.start_event_loop_qt4( app) # doesn't block terminal when run in ipython # app.exec_()
self.vsplit.addWidget(self.control) self.hsplit.addWidget(self.vsplit) self.sendButton = QPushButton("send") #self.sendButton.clicked.connect(self.sendcode) self.vsplit.addWidget(self.sendButton) self.bridge = Js2Py() self.bridge.sent.connect(self.codeFromJs) #lab = QtGui.QLabel(kernel.shell.history_manager.get_range(start=-1).next()[2]) def codeFromJs(self, code): self.control.input_buffer = code if __name__=='__main__': if len(sys.argv) == 1: app = QApplication(sys.argv) app.setApplicationName(APPNAME) main = Snipdom() main.show() def stop(): app.exit() main.onclose = stop main.control.exit_requested.connect(stop) guisupport.start_event_loop_qt4(app)
""" from PyQt4 import QtGui, QtCore class SimpleWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(300, 300, 200, 80) self.setWindowTitle('Hello World') quit = QtGui.QPushButton('Close', self) quit.setGeometry(10, 10, 60, 35) self.connect(quit, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('close()')) if __name__ == '__main__': app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([]) sw = SimpleWindow() sw.show() try: from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) except ImportError: app.exec_()
def procsteppython_do_run(stepglobals, runfunc, argkw, ipythonmodelist, action, scripthref, pycode_text, pycode_lineno): if not ipythonmodelist[0]: resultdict = runfunc(**argkw) return resultdict else: # ipython mode # in-process kernel, a-la https://raw.githubusercontent.com/ipython/ipython/master/examples/Embedding/inprocess_qtconsole.py ## Set PyQt4 API version to 2 and import it -- required for ipython compatibility #import sip #sip.setapi('QVariant', 2) #sip.setapi('QString', 2) #sip.setapi('QDateTime', 2) #sip.setapi('QDate', 2) #sip.setapi('QTextStream', 2) #sip.setapi('QTime', 2) #sip.setapi('QUrl', 2) #from PyQt4 import QtGui # force IPython to use PyQt4 by importing it first # RHEL6 compatibility -- if running under Python 2.6, just import IPython, get PyQt4 if sys.version_info < (2, 7): from IPython.qt.console.rich_ipython_widget import RichIPythonWidget from IPython.qt.inprocess import QtInProcessKernelManager pass else: # Under more recent OS's: Make matplotlib use PySide # http://stackoverflow.com/questions/6723527/getting-pyside-to-work-with-matplotlib import matplotlib matplotlib.use('Qt4Agg') matplotlib.rcParams['backend.qt4'] = 'PySide' pass import IPython from IPython.core.interactiveshell import DummyMod if LooseVersion(IPython.__version__) >= LooseVersion('4.0.0'): # Recent Jupyter/ipython: Import from qtconsole # Force PySide bindings import PySide.QtCore from qtconsole.qt import QtGui from qtconsole.inprocess import QtInProcessKernelManager # Obtain the running QApplication instance app = QtGui.QApplication.instance() if app is None: # Start our own if necessary app = QtGui.QApplication([]) pass pass else: from IPython.qt.inprocess import QtInProcessKernelManager from IPython.lib import guisupport app = guisupport.get_app_qt4() pass kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel() kernel = kernel_manager.kernel kernel.gui = 'qt4' #sys.stderr.write("id(stepglobals)=%d" % (id(stepglobals))) # Make ipython use our globals as its global dictionary # ... but first keep a backup stepglobalsbackup = copy.copy(stepglobals) (kernel.user_module, kernel.user_ns) = kernel.shell.prepare_user_module( user_ns=stepglobals) # Should we attempt to run the function here? # (gui, backend) = kernel.shell.enable_matplotlib("qt4") #,import_all=False) # (args.gui, import_all=import_all) (gui, backend, clobbered) = kernel.shell.enable_pylab( "qt4", import_all=False) # (args.gui, import_all=import_all) # kernel.shell.push(stepglobals) # provide globals as variables -- no longer necessary as it's using our namespace already kernel.shell.push(argkw) # provide arguments as variables kernel.shell.push( {"kernel": kernel}, interactive=False) # provide kernel for debugging purposes kernel_client = kernel_manager.client() kernel_client.start_channels() abort_requested_list = [False ] # encapsulated in a list to make it mutable def stop(): control.hide() kernel_client.stop_channels() kernel_manager.shutdown_kernel() app.exit() pass def abort(): # simple exit doesn't work. See http://stackoverflow.com/questions/1527689/exit-from-ipython # too bad this doesn't work right now!!! class Quitter(object): def __repr__(self): sys.exit() pass kernel.shell.push({"quitter": Quitter()}) kernel.shell.ex("quitter") stop() abort_requested_list.pop() abort_requested_list.append(True) pass if pycode_text is None: kernel.shell.write("\n\nExecute %s/%s\n" % (scripthref.getpath(), runfunc.__name__)) pass else: kernel.shell.write( "\n\nExecute %s/%s/%s\n" % (scripthref.getpath(), action, runfunc.__name__)) pass kernel.shell.write("Assign return value to \"ret\" and press Ctrl-D\n") kernel.shell.write("Set cont=True to disable interactive mode\n") # kernel.shell.write("call abort() to exit\n") if LooseVersion(IPython.__version__) >= LooseVersion('4.0.0'): # Recent Jupyter/ipython: Import from qtconsole from qtconsole.rich_jupyter_widget import RichJupyterWidget as RichIPythonWidget pass else: from IPython.qt.console.rich_ipython_widget import RichIPythonWidget pass control = RichIPythonWidget() control.kernel_manager = kernel_manager control.kernel_client = kernel_client control.exit_requested.connect(stop) control.show() #sys.stderr.write("lines=%s\n" % (str(lines))) #sys.stderr.write("lines[0]=%s\n" % (str(lines[0]))) try: if pycode_text is None: (lines, startinglineno) = inspect.getsourcelines(runfunc) assert (lines[0].startswith("def") ) # first line of function is the defining line del lines[0] # remove def line lines.insert(0, "if 1:\n") # allow function to be indented runfunc_syntaxtree = ast.parse( "".join(lines), filename=scripthref.getpath(), mode='exec' ) # BUG: Should set dont_inherit parameter and properly determine which __future__ import flags should be passed # fixup line numbers for syntreenode in ast.walk(runfunc_syntaxtree): if hasattr(syntreenode, "lineno"): syntreenode.lineno += startinglineno - 1 pass pass # runfunc_syntaxtree should consist of the if statement we just added # use _fields attribute to look up fields of an AST element # (e.g. test, body, orelse for IF) # then those fields can be accessed directly assert (len(runfunc_syntaxtree.body) == 1) code_container = runfunc_syntaxtree.body[0] assert (isinstance(code_container, ast.If) ) # code_container is the if statement we just wrote kernel.shell.push( {"runfunc_syntaxtree": runfunc_syntaxtree}, interactive=False ) # provide processed syntax tree for debugging purposes pass else: fullsyntaxtree = ast.parse( pycode_text ) # BUG: Should set dont_inherit parameter and properly determine which __future__ import flags should be passed # fixup line numbers for syntreenode in ast.walk(fullsyntaxtree): if hasattr(syntreenode, "lineno"): syntreenode.lineno += pycode_lineno - 1 pass pass code_container = None for codeelement in fullsyntaxtree.body: if isinstance(codeelement, ast.FunctionDef): if codeelement.name == runfunc.__name__: code_container = codeelement runfunc_syntaxtree = codeelement pass pass pass if code_container is None: raise ValueError( "Couldn't find code for %s for ipython execution" % (runfunc.__name__)) kernel.shell.push( {"fullsyntaxtree": fullsyntaxtree}, interactive=False ) # provide full syntax tree for debugging purposes pass # identify global variables from runfunc_syntaxtree globalvars = set() for treeelem in ast.walk(runfunc_syntaxtree): if isinstance(treeelem, ast.Global): globalvars = globalvars.union(treeelem.names) pass pass kernel.shell.push({"abort": abort}) # provide abort function kernel.shell.push({"cont": False}) # continue defaults to False returnstatement = code_container.body[-1] if isinstance(returnstatement, ast.Return): # last statement is a return statement! # Create assign statement that assigns # the result to ret retassign = ast.Assign(targets=[ ast.Name(id="ret", ctx=ast.Store(), lineno=returnstatement.lineno, col_offset=returnstatement.col_offset) ], value=returnstatement.value, lineno=returnstatement.lineno, col_offset=returnstatement.col_offset) del code_container.body[-1] # remove returnstatement code_container.body.append(retassign) # add assignment pass runfunc_lines = code_container.body kernel.shell.push( { "runfunc_lines": runfunc_lines, "scripthref": scripthref }, interactive=False ) # provide processed syntax tree for debugging purposes # kernel.shell.run_code(compile("kernel.shell.run_ast_nodes(runfunc_lines,scriptpath,interactivity='all')","None","exec")) if LooseVersion(IPython.__version__) >= LooseVersion('4.0.0'): # Recent Jupyter/ipython: Import from qtconsole from qtconsole.inprocess import QtCore pass else: from IPython.qt.inprocess import QtCore pass QTimer = QtCore.QTimer def showret(): control.execute("ret") pass def runcode(): control.execute( "kernel.shell.run_ast_nodes(runfunc_lines,scripthref.getpath(),interactivity='none')" ) # QTimer.singleShot(25,showret) # get callback 25ms into main loop # showret disabled because it prevents you from running the # debugger in post-mortem mode to troubleshoot an exception: # import pdb; pdb.pm() pass QTimer.singleShot(25, runcode) # get callback 25ms into main loop # control.execute("kernel.shell.run_ast_nodes(runfunc_lines,scripthref.getpath(),interactivity='none')") pass except: (exctype, excvalue) = sys.exc_info()[:2] sys.stderr.write( "%s while attempting to prepare URL %s code for interactive execution: %s\n" % (exctype.__name__, scripthref.absurl(), str(excvalue))) traceback.print_exc() raise if LooseVersion(IPython.__version__) >= LooseVersion('4.0.0'): # Recent Jupyter/ipython: Import from qtconsole app.exec_() pass else: # Old ipython guisupport.start_event_loop_qt4(app) pass if abort_requested_list[0]: pass if kernel.shell.ev("cont"): # cont==True -> disable interactive mode ipythonmodelist.pop() ipythonmodelist.append(False) pass try: retval = kernel.shell.ev( "ret") # Assign result dictionary to "ret" variable pass except NameError: # if ret not assigned, return {} retval = {} pass # Performing this execution changed values in stepglobals # but it should have only done that for variables specified # as 'global' in the function. # So: Update our backup of the value of stepglobals, # according to the specified globals, and # replace stepglobals with that updated backup stepglobalsbackup.update( dict([(varname, stepglobals[varname]) for varname in globalvars])) stepglobals.clear() stepglobals.update(stepglobalsbackup) return retval pass
try: from IPython.lib import guisupport as gui from IPython.lib.inputhook import InputHookManager # create class managing hook for event loop in ipython hook = InputHookManager() # get the QApplication, creating one if not existing app = gui.get_app_qt4() # add the application to the hook hook.enable_qt4(app) # if event loop not running, run it for ipython if not gui.is_event_loop_running_qt4(app): gui.start_event_loop_qt4(app) except: pass class Figure(QGraphicsView): def __init__(self, *args, **kwargs): super(Figure, self).__init__(*args, **kwargs) # Creation of the Plotting class: # Then we add it as background of the View: self._context = QGLWidget(QGLFormat(QGL.NoAccumBuffer)) self.setViewport(self._context)