The code is keep getting error when click on the canvas. How to fix this error? I would like to know where this error comes from. Thank you!Do I need to make a mouse clicking event? I would like to know what is a better way to fix this error.
import mplcursors
import numpy as np
from PyQt6.QtWidgets import QApplication, QSizePolicy, QWidget, QVBoxLayout
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
class CustomCanvas(FigureCanvas):
def __init__(self, parent=None):
self.figure = Figure()
super().__init__(self.figure)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
def draw_heatmap(self, data):
self.figure.clear()
ax = self.figure.add_subplot(111)
heatmap = ax.imshow(data, cmap='coolwarm', interpolation='nearest', aspect='auto')
self.figure.colorbar(heatmap)
self.draw()
cursor = mplcursors.cursor(heatmap, hover=True)
@cursor.connect("add")
def on_hover(sel):
x, y = sel.index
value = data[y, x]
sel.annotation.set_text(f"Value: {value:.2f}")
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# Create the main layout
main_layout = QVBoxLayout(self)
# Create a custom canvas widget
canvas = CustomCanvas()
# Generate example heatmap data
data = np.random.rand(10, 10)
# Draw the heatmap
canvas.draw_heatmap(data)
# Add the canvas widget to the layout
main_layout.addWidget(canvas)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
Here is the terminal showed:
Traceback (most recent call last):
File "C:\Users\Python\Python311\Lib\site-packages\matplotlib\cbook\__init__.py", line 304, in process
func(*args, **kwargs)
File "C:\Users\Python\Python311\Lib\site-packages\matplotlib\offsetbox.py", line 1550, in on_release
if self._check_still_parented() and self.got_artist:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Python\Python311\Lib\site-packages\matplotlib\offsetbox.py", line 1560, in _check_still_parented
self.disconnect()
File "C:\Users\Python\Python311\Lib\site-packages\matplotlib\offsetbox.py", line 1568, in disconnect
self.canvas.mpl_disconnect(cid)
^^^^^^^^^^^
File "C:\Users\Python\Python311\Lib\site-packages\matplotlib\offsetbox.py", line 1517, in <lambda>
canvas = property(lambda self: self.ref_artist.figure.canvas)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'canvas'