如何使PyQt5中的matplotlib小部件可单击?

2024-04-23 15:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在GUI上工作,我有一个带有图形的选项卡系统。我希望,如果用户单击(或放置光标)图形中的任意点,它会显示该点的确切x和y值,如下所示:

picture

我知道在通常的matplotlib中很容易实现;然而,我不知道如何在PyQt5中做到这一点

我的标签系统和画布如下所示:

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QApplication, QWidget,QVBoxLayout,QTabWidget
import sys
import matplotlib.pyplot as plt

def mouse_move(event):
    x, y = event.xdata, event.ydata
    print(x, y)


plt.connect('motion_notify_event', mouse_move)

class Canvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=5, dpi=80):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self.plot()


    def plot(self):
            x = ['22-02 11:16:15', '22-02 15:31:54', '22-02 15:32:30',
                 '22-02 15:32:45', '22-02 15:33:57', '22-02 15:34:13',
             '22-02 15:34:46']
            y = [1, 4, 3, 4, 8, 9, 2]
            self.figure.tight_layout()
            ax = self.figure.add_subplot(111)
            ax.plot(x, y)


class MainWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.top = 255
        self.left = 150
        self.setGeometry(self.left, self.top, 900, 900)
        self.Mainlayout = QVBoxLayout(self)
        self.tabs = QTabWidget()
        self.graphUP = QWidget()
        self.graphUP.layout = QVBoxLayout( self.graphUP)
        self.graphUP.layout.addWidget(Canvas())
        self.tabs.setFixedHeight(800)
        self.tabs.setFixedWidth(800)
        self.tabs.addTab(self.graphUP, "Graph1")
        self.Mainlayout.addWidget(self.tabs)
        self.show()


if __name__ == '__main__':
    App = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(App.exec())

Tags: fromimportselfeventmatplotlibinitdefsys