I am use pyqt5 to draw a simple chart and need to add custom axis, but when i add axis , the chart not show it, and when hovered signal emit, i need to show corresponding point , but it also not showing, it need to click to show.
class Demo(QChartView):
def __init__(self):
super().__init__()
self.chart = QChart()
self.setChart(self.chart)
self.setRenderHint(QPainter.Antialiasing)
axis_x = QValueAxis()
axis_x.setTickCount(10)
axis_x.setTitleText('x')
self.chart.addAxis(axis_x, Qt.AlignBottom)
axis_y= QValueAxis()
axis_y.setLinePenColor(Qt.red)
self.chart.addAxis(axis_y, Qt.AlignLeft)
series = QLineSeries()
series.setPointsVisible(True)
series.hovered.connect(self.show_tool_tip)
series << QPointF(1, 5) << QPointF(3.5, 18) << QPointF(4.8, 7.5) << QPointF(10, 2.5)
series.attachAxis(axis_x)
series.attachAxis(axis_y)
self.chart.addSeries(series)
self.value_label = QLabel(self)
def show_tool_tip(self, pt, state):
pos = self.chart.mapToPosition(pt)
if state:
self.value_label.move(int(pos.x()), int(pos.y()))
self.value_label.setText(f'{pt}')
self.value_label.show()
else:
self.value_label.hide()
If you run your code in a console/CMD you will get the following command:
Series not in the chart. Please addSeries to chart first.
Series not in the chart. Please addSeries to chart first.
That clearly indicates that you must first add the series to the QChart and then add the axes:
self.chart.addSeries(series) # first add the series
series.attachAxis(axis_x)
series.attachAxis(axis_y)
The problem is that since the line is so thin, the mouse goes out and enters making the hovered be emitted at every moment, making it appear to be hidden from our eyes.
Awaiting answer to my comment to propose a solution.