使用缩放线示例,我创建了一个Python QChartView
类,可以使用箭头键滚动并使用加号和减号键进行缩放(请参阅下面的我的代码)。
当我向左滚动时,我希望网格线和轴刻度与数据一起滚动。然而,只有数据(QLineSeries)向左滚动。5个网格线仍然保持在相同的位置,但其刻度值已更新。这是不可取的,因为新的刻度值可能是任何值。
我在文档中查找过,但没有找到如何使网格与数据一起滚动。我错过了什么吗?
我还想能够将刻度设置为显式值(以便我可以自己实现滚动行为)。是否可以将轴刻度值设置为特定值?
我的示例代码:
import sys
from math import pi, sin, sqrt
from PyQt5.QtChart import QLineSeries, QChart, QChartView
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
class ZoomPanChartView(QChartView):
""" QChartView that can zoom/pan with the keys
"""
def __init__(self, chart):
super().__init__(chart)
self.zoomFactor = sqrt(2) # QCharts default is 2
self.panPixels = 10
def keyPressEvent(self, keyEvent):
""" Panning (scrolling) is done with the arrow keys.
Zooming goes with the plus and minus keys.
The '=' key resets.
"""
key = keyEvent.key()
if key == Qt.Key_Equal:
self.chart().zoomReset()
if key == Qt.Key_Plus:
self.chart().zoom(self.zoomFactor)
elif key == Qt.Key_Minus:
self.chart().zoom(1/self.zoomFactor)
elif key == Qt.Key_Left:
self.chart().scroll(-self.panPixels, 0)
elif key == Qt.Key_Right:
self.chart().scroll(+self.panPixels, 0)
elif key == Qt.Key_Up:
self.chart().scroll(0, +self.panPixels)
elif key == Qt.Key_Down:
self.chart().scroll(0, -self.panPixels)
elif key == Qt.Key_0:
self.chart().axisX().applyNiceNumbers() # changes the range
else:
super().keyPressEvent(keyEvent)
def main():
app = QApplication(sys.argv)
chart = QChart()
series = QLineSeries()
for i in range(0, 100):
x = i * pi / 20
y = sin(x)
series.append(x, y)
chart.addSeries(series)
chart.createDefaultAxes()
chart.axisY().setRange(-1, 1)
chart.legend().hide()
chartView = ZoomPanChartView(chart)
chartView.show()
chartView.resize(400, 300)
sys.exit(app.exec_())
if __name__ == "__main__":
main()