1

我想在QChart中制作一个橡皮筋窗口,但是我不知道如何将QChart的坐标映射到QChartView。

eg (0, 0) 是一个QChart 坐标,在QChartView 中可能是(10, 10),怎么转换呢?我已经看到在 QChartView 的轴系中获取鼠标坐标 的答案

但它似乎与我的要求相反。

import sys
from PyQt5.QtChart import QChart, QChartView, QLineSeries
from PyQt5.QtCore import QPointF, QEvent, QPoint, QRect
from PyQt5.QtWidgets import QApplication, QMainWindow, QRubberBand

class ChartView(QChartView):
    def init_rubber_band(self):
        chart = self.chart()

        start1 = chart.mapToPosition(QPointF(0, 0))
        start2 = chart.mapToScene(start1)
        start3 = QPoint()
        start3.setX(int(start2.x()))
        start3.setY(int(start2.y()))

        end = QPoint(200, 200)

        self.rubber = QRubberBand(QRubberBand.Rectangle, self);
        self.rubber.setGeometry(QRect(start3, end))
        self.rubber.show()


app = QApplication(sys.argv)
series0 = QLineSeries()
series1 = QLineSeries()

series0 << QPointF(1, 15) << QPointF(3, 17) << QPointF(7, 16) << QPointF(9, 17) \
        << QPointF(12, 16) << QPointF(16, 17) << QPointF(18, 15)
series1 << QPointF(1, 3) << QPointF(3, 4) << QPointF(7, 3) << QPointF(8, 2) \
        << QPointF(12, 3) << QPointF(16, 4) << QPointF(18, 3)

chart = QChart()
chart.addSeries(series0)
chart.addSeries(series1)
chart.createDefaultAxes()
chartView = ChartView(chart)

chartView.init_rubber_band()

window = QMainWindow()
window.setCentralWidget(chartView)
window.resize(400, 300)
window.show()

sys.exit(app.exec_())

mapToPosition用来获取原点的坐标,但似乎它不起作用。

4

1 回答 1

1

如果你想执行一些计算,你必须在小部件显示后进行,因为QChartView只是重新计算项目,在下面的例子中,我将QRubberBand在一个矩形上创建一个坐标,QChartQPointF(1, 17)QPointF(18, 2)

class ChartView(QChartView):
    def init_rubber_band(self):
        chart = self.chart()
        start_value = QPointF(1, 17)
        end_value = QPointF(18, 2)
        start = chart.mapToPosition(start_value)
        end = chart.mapToPosition(end_value)

        self.rubber = QRubberBand(QRubberBand.Rectangle, self)
        self.rubber.setGeometry(QRect(start.toPoint(), end.toPoint()))
        self.rubber.show()


app = QApplication(sys.argv)
series0 = QLineSeries()
series1 = QLineSeries()

series0 << QPointF(1, 15) << QPointF(3, 17) << QPointF(7, 16) << QPointF(9, 17) \
        << QPointF(12, 16) << QPointF(16, 17) << QPointF(18, 15)
series1 << QPointF(1, 3) << QPointF(3, 4) << QPointF(7, 3) << QPointF(8, 2) \
        << QPointF(12, 3) << QPointF(16, 4) << QPointF(18, 3)

chart = QChart()
chart.addSeries(series0)
chart.addSeries(series1)
chart.createDefaultAxes()
chartView = ChartView(chart)

window = QMainWindow()
window.setCentralWidget(chartView)
window.resize(400, 300)
window.show()

chartView.init_rubber_band()

sys.exit(app.exec_())

输出:

在此处输入图像描述

于 2018-02-23T03:16:55.990 回答