【发布时间】:2018-01-21 16:57:58
【问题描述】:
Matplotlib 如何为 Qt 等后端库设置事件循环,同时仍允许通过 python REPL 进行交互?至少对于 Qt 来说,主事件循环必须在主线程中运行,但这就是 REPL 所在的地方,对,所以我正在努力看看这两者如何共存。
我当前的尝试在单独的 Python 中启动 QApplication
threading.Thread
def mainloop():
app = QtWidgets.QApplication([])
while True:
app.processEvents()
time.sleep(0.01)
t = threading.Thread(target=mainloop)
t.daemon = True
t.start()
哪种方法有效,但我收到此警告,有时会崩溃:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QApplication(0x7fc5cc001820), parent's thread is QThread(0x7fc5cc001a40), current thread is QThread(0x2702160)
更新 1
这是使用QThread的尝试:
from PyQt5 import QtGui, QtCore, QtWidgets
import time
class Mainloop(QtCore.QObject):
def __init__(self):
super().__init__()
self.app = QtWidgets.QApplication([])
def run(self):
while True:
self.app.processEvents()
time.sleep(1)
t = QtCore.QThread()
m = Mainloop()
m.moveToThread(t)
t.started.connect(m.run)
t.start()
# Essentially I want to be able to interactively build a GUI here
dialog = QtWidgets.QDialog()
dialog.show()
更新 2
基本上,我想模拟以下 interactive python 会话,即不将其作为脚本运行以呈现现成的 GUI。是什么让图形窗口的外观不阻塞python解释器?
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
Type "copyright", "credits" or "license" for more information.
IPython 5.2.2 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import matplotlib.pyplot as plt
In [2]: plt.ion()
In [3]: fig = plt.figure()
In [4]: # The last command opens a figure window which remains responsive.
...: I can resize it and the window redraws, yet I can still interact
...: with the python interpreter and interactively add new content to t
...: he figure
In [5]: ax = fig.add_subplot(111)
In [6]: # The last command updated the figure window and I can still inter
...: act with the interpreter
In [7]:
【问题讨论】:
-
感谢您的回复。忘了提到我还使用
app.exec_()尝试了不同的版本。不知道我是否误会了什么。我没有使用 app.exec_() 的原因是因为它会在 Qt 主事件循环中阻止 python REPL。你能解释一下为什么这应该有效吗? -
我尝试使用 QThread 更新了问题。我可以在 Update 1 中运行代码而不会出现错误,但是
QDialog没有响应,也就是说,当我调整窗口大小时它不会重新绘制窗口,所以我猜 Qt 事件没有处理事件循环。
标签: python matplotlib pyqt