xwsz
xwsz

Reputation: 37

How to display multicursor on a QTabWidget?

The multicursor example

The question is : If I want the plot to be displayed on a tab of the QTabWidget,how to make the MultiCursor works?

# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import numpy as np
import sys
from matplotlib.gridspec import GridSpec
from matplotlib.widgets import MultiCursor
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas    

class MainWindow(QMainWindow):

def __init__(self):

    super().__init__(flags=Qt.Window)
    self.setFont(QFont("Microsoft YaHei", 10, QFont.Normal))
    self.setMinimumSize(1550, 950)
    self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
    centralwidget = QWidget(flags=Qt.Widget)
    centralwidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
    self.setCentralWidget(centralwidget)
    self.tabview = QTabWidget()
    self.tabview.currentChanged.connect(self.onchange)
    self.chart_widget0 = QWidget()
    self.chart_widget1 = QWidget()
    self.dc0 = my_Canvas(self.chart_widget0, width=20, height=8, dpi=100)
    self.dc1 = my_Canvas(self.chart_widget1, width=20, height=8, dpi=100)
    self.tabview.addTab(self.dc0, "MultiCursor")
    self.tabview.addTab(self.dc1, "Cursor")

    toplayout = QHBoxLayout()
    toplayout.addWidget(self.tabview)
    centralwidget.setLayout(toplayout)

def onchange(self,i):

    if i == 0:
        self.dc0.update_figure()
    elif i == 1:
        self.dc1.update_figure()

class my_Canvas(FigureCanvas):

def __init__(self, parent=None, width=10, height=7, dpi=100):

    self.fig = plt.figure(figsize=(width, height), dpi=dpi)
    gs = GridSpec(2, 1, height_ratios=[3, 1])
    self.axes1 = plt.subplot(gs[0])
    self.axes2 = plt.subplot(gs[1])

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

def compute_initial_figure(self):

    self.axes1.cla()
    self.axes2.cla()

def update_figure(self):

    t = np.arange(0.0, 2.0, 0.01)
    s1 = np.sin(2*np.pi*t)
    s2 = np.sin(4*np.pi*t)
    self.axes1.plot(t, s1)
    self.axes2.plot(t, s2)
    multi = MultiCursor(self.fig.canvas, (self.axes1, self.axes2), color='r', lw=1)
    self.draw()

if __name__ == '__main__':
app = QApplication(sys.argv)
w1 = MainWindow()
w1.show()
sys.exit(app.exec_())

How to modify the code to make the MultiCursor works, and could I control the display of the cursor by key or mousebutton click?

Further more, how to display the coordinate with the cursor?

Upvotes: 1

Views: 137

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339430

As the Multicursor documentation tells us,

For the cursor to remain responsive you must keep a reference to it.

The easiest way is to make it a class variable,

self.multi = MultiCursor(...)

Upvotes: 1

Related Questions