我希望在matplotlib
窗口的光标处有一个十字准线。这在matplotlib gallery中给出的示例中有效。但不幸的是,如果我在Qt对话框窗口(QDialog
)中有matplotlib小部件,它就不起作用。
这是我的代码示例,我想要实例化matplotlib.widgets.Cursor
对象,但没有显示任何内容。
import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.figure = plt.figure(facecolor='white')
self.canvas = FigureCanvas(self.figure)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.canvas)
self.setLayout(layout)
''' plot some random stuff '''
ax = self.figure.add_subplot(111)
self.ax = ax
ax.plot([1,2])
# Set cursor
Cursor(self.ax, useblit=False, color='red', linewidth=1)
self.canvas.draw()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
有人可以帮忙吗?
答案 0 :(得分:2)
我已按如下方式修改了您的代码,它可以在我的计算机上运行。希望它有所帮助。
import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.figure = plt.figure(facecolor='white')
self.canvas = FigureCanvas(self.figure)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.canvas)
self.setLayout(layout)
''' plot some random stuff '''
ax = self.figure.add_subplot(111)
self.ax = ax
ax.plot([1,2])
# Set cursor
cursor = Cursor(self.ax, useblit=False, color='red', linewidth=1)
############## The added part: #############
def onclick(event):
cursor.onmove(event)
self.canvas.mpl_connect('button_press_event', onclick)
############################################
self.canvas.draw()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
答案 1 :(得分:0)
(1)中的原始代码:Cursor(self.ax, useblit=False, color='red', linewidth=1)
并没有如文档中所示引用游标。
(2)中的代码具有赋值,但没有赋值给类引用,而是赋给了局部变量:
cursor = Cursor(self.ax, useblit=False, color='red', linewidth=1)
(2)中的代码可以使用指示的附加功能,但是光标移动缓慢。
解决方案是(1)中的代码,但修改如下:
self.cursor = Cursor(self.ax, useblit=False, color='red', linewidth=1)