我想在QT小部件中嵌入一个Ipython终端,这样我就可以访问QT应用程序中的对象。我理解这可以通过以下示例实现:https://github.com/gpoulin/python-test/blob/master/embedded_qtconsole.py 但是,如果内核阻塞(例如在无限循环中)整个应用程序没有响应,只能使用来自运行qt应用程序的终端的键盘中断来终止。如果我使用QtKernelManager而不是QtInProcessKernelManager,我可以成功地从qt应用程序中断内核,但是,由于内核嵌入在不同的进程中,我无法访问其中的对象。 在同一进程中嵌入IPython终端时,有没有办法捕获键盘中断?或者我应该使用嵌入内核的不同实现?
我改编的代码位于
之下import os
os.environ['QT_API'] = 'pyqt'
import sip
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)
import sys
from PyQt4 import QtGui, QtCore
from pkg_resources import require
require('ipython')
from IPython.qt.console.rich_ipython_widget import RichIPythonWidget
from IPython.qt.inprocess import QtInProcessKernelManager
class IPythonWidget(QtGui.QWidget):
def __init__(self, **kwarg):
super(IPythonWidget, self).__init__()
self.initUI()
def startIpKernel(self):
self.kernel_manager = QtInProcessKernelManager()
self.kernel_manager.start_kernel()
self.kernel_manager.kernel.gui = 'qt4'
self.kernel_client = kernel_client = self.kernel_manager.client()
self.kernel_client.start_channels()
def initUI(self):
self.startIpKernel()
self.addWidgets()
def addWidgets(self):
self.button = QtGui.QPushButton()
self.button.setText("test button")
self.console = RichIPythonWidget(self)
self.console.kernel_manager =self.kernel_manager
self.console.kernel_client = self.kernel_client
self.console.kernel_manager.kernel.shell.push({"button": self.button})#this can be wrapped into another method
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.console)
vbox.addWidget(self.button)
self.setLayout(vbox)
def mousePressEvent(self, event):
self.mousepos = event.pos()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = IPythonWidget()
ex.show()
sys.exit(app.exec_())