PyQt:在图表中抓取mouseMoveEvent

时间:2017-01-29 15:38:54

标签: python qt user-interface pyqt

我有以下PyQt代码:

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtChart import QChart, QChartView, QLineSeries, QValueAxis
from PyQt5 import QtCore, QtGui

class MainWindow(QMainWindow):
    class ChartView(QChartView):
        def __init__(self, chart):
            super().__init__(chart)        

        def mouseMoveEvent(self, event):
            print("ChartView.mouseMoveEvent", event.pos().x(), event.pos().y())

            return QChartView.mouseMoveEvent(self, event)

    class Chart(QChart):
        def __init__(self):
            super().__init__()

        def mouseMoveEvent(self, event):
            print("Chart.mouseMoveEvent", event.pos().x(), event.pos().y())

            return QChart.mouseMoveEvent(self, event)

    def __init__(self, args):
        super().__init__()

        chartView = self.ChartView(self.Chart())
        chartView.setRenderHint(QtGui.QPainter.Antialiasing)
        chartView.setRubberBand(QChartView.HorizontalRubberBand)

        chartView.chart().createDefaultAxes()
        chartView.chart().legend().hide()
        chartView.chart().addAxis(QValueAxis(), QtCore.Qt.AlignBottom)
        chartView.chart().addAxis(QValueAxis(), QtCore.Qt.AlignLeft)

        ls = QLineSeries()
        ls.append(0, 0)
        ls.append(9, 9)
        ls.attachAxis(chartView.chart().axisX())
        ls.attachAxis(chartView.chart().axisY())
        chartView.chart().addSeries(ls)

        self.setCentralWidget(chartView)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    mainWindow = MainWindow(sys.argv)
    sys.exit(app.exec_())

问题在于,上面的代码mouseMoveEvent仅针对ChartView发出。但我想为mouseMoveEvent而不是Chart发出ChartView。我怎么能做到这一点?如果mouseMoveEvent无法触发Chart,我怎样才能将event.pos()转换为QChart内的ChartView.mouseMoveEvent坐标?

1 个答案:

答案 0 :(得分:1)

好的,最后我找到了办法。我从mouseMoveEvent重新实现ChartView并让它发出信号mouseMoved

class ChartView(QChartView):
    # ...

    mouseMoved = QtCore.pyqtSignal(QtCore.QPoint)

    def mouseMoveEvent(self, event):
        self.mouseMoved.emit(event.pos())

        return QChartView.mouseMoveEvent(self, event)

此信号我连接到Chart

的插槽
chartView.mouseMoved.connect(chartView.chart().mouseMoved)

在插槽中,我使用Chart将坐标转换为mapFromParent坐标系;我甚至可以使用mapToValue

将其映射到系列的坐标系中
class Chart(QChart):
    # ...

    def mouseMoved(self, pos):
        print("Chart.mouseMoved parent coord domain: ", pos)
        print("Chart.mouseMoved own coord domain:", self.mapFromParent(pos))
        print("chart.mouseMoved line series coord domain:", self.mapToValue(self.mapFromParent(pos), self.series()[0]))