matplotlib 滑块嵌入 pyqt6 应用程序时不起作用

问题描述 投票:0回答:1

我无法让 matplotlib 滑块在 PyQt6 应用程序内做出响应。这是一个示例程序。我知道滑块上没有绑定(这不是问题)。问题是滑块本身不响应鼠标事件(即单击、拖动)。

我正在使用 python 3.10.12、matplotlib 3.8.2、PyQt6 6.6.1


import numpy as np

from matplotlib.backends.backend_qtagg import FigureCanvas
from matplotlib.backends.backend_qtagg import \
    NavigationToolbar2QT as NavigationToolbar
from matplotlib.backends.qt_compat import QtWidgets
from matplotlib.figure import Figure
from matplotlib.widgets import Slider

class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        layout = QtWidgets.QVBoxLayout(self._main)

        fig = Figure(figsize=(5, 3))
        static_canvas = FigureCanvas(fig)
        layout.addWidget(NavigationToolbar(static_canvas, self))
        layout.addWidget(static_canvas)

        self._static_ax = static_canvas.figure.subplots()
        t = np.linspace(0, 10, 501)
        self._static_ax.plot(t, np.tan(t), ".")

        fig.subplots_adjust(left=0.25)

        axamp = fig.add_axes([0.1, 0.25, 0.0225, 0.63])
        amp_slider = Slider(
            ax=axamp,
            label="Amplitude",
            valmin=0,
            valmax=10,
            valinit=6,
            orientation="vertical"
        )

        amp_slider.on_changed(self.slider_callback)
    
    def slider_callback(self):
        print("slider is changing")

if __name__ == "__main__":
    # Check whether there is already a running QApplication (e.g., if running
    # from an IDE).
    qapp = QtWidgets.QApplication.instance()
    if not qapp:
        qapp = QtWidgets.QApplication(sys.argv)

    app = ApplicationWindow()
    app.show()
    app.activateWindow()
    app.raise_()
    qapp.exec()
python matplotlib pyqt pyqt6 matplotlib-widget
1个回答
0
投票

根据@relent95的评论,我只需要存储对滑块实例的引用。

self.amp_slider = Slider(...)

© www.soinside.com 2019 - 2024. All rights reserved.