【问题标题】:qt chart move view with pressed middle mouse buttonqt图表移动视图按下鼠标中键
【发布时间】:2018-05-24 02:48:30
【问题描述】:

我目前正在使用 Qts 图表绘图工具。我现在有一个绘图,我可以使用this 示例提供的图表视图类进行放大和缩小(稍作调整)。 我希望看到不仅可以缩放,还可以通过按下鼠标中键移动我的视图(这在其他应用程序中经常使用,因此非常直观)。

如何在 Qt 中做到这一点?如何检查鼠标中键是否被按下和释放,如果鼠标在按下鼠标中键期间移动,如何更改我在绘图中的视图...

我确定有人之前已经编写过此代码,并且非常感谢您提供一个小示例/帮助。

【问题讨论】:

标签: c++ qt qtcharts


【解决方案1】:

您需要从QChartView 派生一个类并重载鼠标事件:

class ChartView: public QChartView
{
    Q_OBJECT

public:
    ChartView(Chart* chart, QWidget *parent = 0);

protected:

    virtual void mousePressEvent(QMouseEvent *event) override;
    virtual void mouseMoveEvent(QMouseEvent *event) override;

private:

    QPointF m_lastMousePos;
};

ChartView::ChartView(Chart* chart, QWidget *parent)
    : QChartView(chart, parent)
{
    setDragMode(QGraphicsView::NoDrag);
    this->setMouseTracking(true);
}

void ChartView::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::MiddleButton)
    {
        QApplication::setOverrideCursor(QCursor(Qt::SizeAllCursor));
        m_lastMousePos = event->pos();
        event->accept();
    }

    QChartView::mousePressEvent(event);
}

void ChartView::mouseMoveEvent(QMouseEvent *event)
{
    // pan the chart with a middle mouse drag
    if (event->buttons() & Qt::MiddleButton)
    {
        QRectF bounds = QRectF(0,0,0,0);
        for(auto series : this->chart()->series())
            bounds.united(series->bounds())

        auto dPos = this->chart()->mapToValue(event->pos()) - this->chart()->mapToValue(m_lastMousePos);

        if (this->rubberBand() == QChartView::RectangleRubberBand)
            this->chart()->zoom(bounds.translated(-dPos.x(), -dPos.y()));
        else if (this->rubberBand() == QChartView::HorizontalRubberBand)
            this->chart()->zoom(bounds.translated(-dPos.x(), 0));
        else if (this->rubberBand() == QChartView::VerticalRubberBand)
            this->chart()->zoom(bounds.translated(0, -dPos.y()));

        m_lastMousePos = event->pos();
        event->accept();
    }

    QChartView::mouseMoveEvent(event);
}

【讨论】:

  • 什么是 m_zoomRect?
  • 这是一个更大的项目 (github.com/nholthaus/chart) 的一部分,该项目还扩展了图表并处理了缩放。我已经编辑了答案,但在这种情况下,m_zoomRect 是所有图表系列边界的并集。
【解决方案2】:

我想提供 Nicolas 的 mouseMoveEvent() 的更简单版本:

    void ChartView::mouseMoveEvent(QMouseEvent *event)
    {
        // pan the chart with a middle mouse drag
        if (event->buttons() & Qt::MiddleButton)
        {
            auto dPos = event->pos() - lastMousePos_;
            chart()->scroll(-dPos.x(), dPos.y());

            lastMousePos_ = event->pos();
            event->accept();

            QApplication::restoreOverrideCursor();
        }

        QChartView::mouseMoveEvent(event);
    }

另外,请务必包含QApplication::restoreOverrideCursor(),以便在移动完成后光标恢复正常。

【讨论】:

  • 您需要先初始化lastMousePos_。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多