gpt4 book ai didi

python - 无法在 Qt 应用程序内重绘 matplot

转载 作者:行者123 更新时间:2023-11-30 22:26:21 24 4
gpt4 key购买 nike

我想调用matplotlibdraw()方法,用于更新已更改但未自动重新绘制的图形。请注意,该图是在 QT 应用程序内部构建的。以下是错误跟踪:

Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/matplotlib/cbook/__init__.py", line 389, in process
proxy(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/cbook/__init__.py", line 227, in __call__
return mtd(*args, **kwargs)
File "matplotlib_qt.py", line 43, in mouseClick
self.myMplCanvas.fig.draw()
TypeError: draw_wrapper() takes at least 2 arguments (1 given)

在独立的matplotlib应用程序中,可以轻松地调用draw方法,如下所示:

import matplotlib.pyplot as plt

fig = plt.figure()
# plot here and change plot variables later
# now re-draw it
plt.draw()

下面是完整的QT应用代码:

import sys
from matplotlib.backends import qt_compat
use_pyside = qt_compat.QT_API == qt_compat.QT_API_PYSIDE
if use_pyside:
from PySide import QtGui, QtCore
else:
from PyQt4 import QtGui, QtCore

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.image as mpimg

class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = self.fig.add_subplot(111)

img = mpimg.imread('stinkbug.png')
lum_img = img[:, :, 0]
self.axes.imshow(lum_img)

FigureCanvas.__init__(self, self.fig)
self.setParent(parent)

FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)

class ApplicationWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setWindowTitle("application main window")

self.main_widget = QtGui.QWidget(self)
l = QtGui.QVBoxLayout(self.main_widget)
self.myMplCanvas = MyMplCanvas(self.main_widget, width=5, height=4, dpi=100)
l.addWidget(self.myMplCanvas)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
self.myMplCanvas.mpl_connect('button_press_event', self.mouseClick)

def mouseClick(self, event):
self.myMplCanvas.fig.draw()


qApp = QtGui.QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("hello")
aw.show()
sys.exit(qApp.exec_())

这里出了什么问题?请提供任何解决方法。

最佳答案

请注意,如果 fig 是图形,则 plt.draw()fig.draw() 不同。为了绘制图形,需要提供渲染器。

但是,您可能想要绘制 Canvas 而不是图形。

fig.canvas.draw() # <- not recommended
# better:
fig.canvas.draw_idle()

在这个问题中,您已经将 Canvas 作为 self.myMplCanvas,因此您可以调用

self.myMplCanvas.draw_idle()

关于python - 无法在 Qt 应用程序内重绘 matplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47246446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com