2

在我的应用程序中,当用户移动鼠标时,我需要画一条线。但是当图表窗口第一次显示并移动鼠标时,线超出了边界。i 调整窗口大小,它工作正常。我不知道为什么第一次启动窗口它不能正常工作,似乎第一次和之后没有什么不同。

代码是:

import random
from PyQt5.QtChart import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class DemoChar(QChartView):
    def __init__(self):
        super().__init__()
        self.setRenderHint(QPainter.Antialiasing)
        self.chart = QChart()
        self.chart.setTitle('Demo')
        self.chart.setAnimationOptions(QChart.SeriesAnimations)
        self.setChart(self.chart)
        self.lineItem = QGraphicsLineItem(self.chart)

        series = QLineSeries(name="random serie")
        series.setPointsVisible(True)

        for i in range(20):
            series << QPointF(0.1 * i, random.uniform(-10, 10))

        self.chart.addSeries(series)
        self.chart.createDefaultAxes()
        axis_x, axis_y = self.chart.axes()

        #get axis min, max value to calculate position
        self.min_x, self.min_y = axis_x.min(), axis_y.min()
        self.max_x, self.max_y = axis_x.max(), axis_y.max()

    def resizeEvent(self, event):
        super().resizeEvent(event)

        self.point_bottom = self.chart.mapToPosition(QPointF(self.min_x, self.min_y))
        self.point_top = self.chart.mapToPosition(QPointF(self.min_x, self.max_y))

        line = self.lineItem.line()
        line.setLine(line.x1(), self.point_bottom.y(), line.x2(), self.point_top.y() )
        self.lineItem.setLine(line)

    def mouseMoveEvent(self, event):
        super().mouseMoveEvent(event)
        pt = self.chart.mapToValue(event.pos())

        if not (self.min_x <= pt.x() <= self.max_x):
            self.lineItem.hide()
            return

        for marker in self.chart.legend().markers():
            if marker.series().isVisible():
                points = marker.series().pointsVector() #type:list
                for point in points:
                    left_idx = points.index(point)
                    right_point = points[left_idx + 1]
                    if point.x() <= pt.x() <= right_point.x():
                        left_delta = pt.x() - point.x()
                        right_delta = right_point.x() - pt.x()

                        if left_delta < right_delta:
                            pos = self.chart.mapToPosition(point)
                            self.lineItem.setLine(pos.x(), self.point_bottom.y(), pos.x(), self.point_top.y() )
                            self.lineItem.show()
                        break

app = QApplication([])
demo = DemoChar()
demo.show()
app.exec()

首先像这样启动并移动鼠标。

1

然后调整窗口大小,它工作正常。

2

4

1 回答 1

1

绘制和resizeEvent之间似乎存在差距,可能是一个错误。一种解决方法是通过代码修改大小:

# ...
self.min_x, self.min_y = axis_x.min(), axis_y.min()
self.max_x, self.max_y = axis_x.max(), axis_y.max()

self.resize(self.size() + QSize(1, 1))
于 2019-11-02T03:59:44.113 回答