簡體   English   中英

使用鼠標滾輪縮放QChartView的x軸

[英]Scale x-axis of QChartView using mouse wheel

在我的應用程序中,我使用QChart顯示折線圖。 不幸的是,Qt Charts不支持基本功能,例如使用鼠標滾輪縮放和使用鼠標滾動。 是的,有RubberBand功能,但仍然不支持用戶不那么直觀的滾動等結尾。 另外,我只需要縮放x軸,使用setRubberBand(QChartView::HorizontalRubberBand)但使用鼠標滾輪即可。 到目前為止,在深入研究QChartView我使用了以下解決方法:

class ChartView : public QChartView {
protected:
    void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE
    {
        QRectF rect = chart()->plotArea();            
        if(event->angleDelta().y() > 0)
        {
            rect.setX(rect.x() + rect.width() / 4);
            rect.setWidth(rect.width() / 2);                                   
        }
        else
        {
            qreal adjustment = rect.width() / 2;
            rect.adjust(-adjustment, 0, adjustment, 0);                    
        }            
        chart()->zoomIn(rect);
        event->accept();            
        QChartView::wheelEvent(event);
    }
}

那行得通,但放大然后縮小不會導致相同的結果。 有一個小的偏差。 調試后,我發現chart()->plotArea()始終返回相同的rect,因此此解決方法沒有用。

是否有某種方法只能獲得可見區域的校正? 還是有人可以為我指出正確的解決方案,如何使用鼠標對QChartView進行縮放/滾動?

除了使用zoomIn()zoomOut()還可以使用zoom() ,如下所示:

class ChartView : public QChartView {
protected:
    void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE
    {
        qreal factor = event->angleDelta().y() > 0? 0.5: 2.0;
        chart()->zoom(factor);
        event->accept();
        QChartView::wheelEvent(event);
    }
};

關於zoomIn()zoomOut() ,尚不清楚它所指的是哪種坐標,我仍在投資,當我有更多信息時,將更新我的答案。

更新:

正如我觀察到的那樣,問題之一是浮點數的乘積,另一個是定位圖形的中心,為了不出現這些問題,我的解決方案重置了縮放比例,然后設置了更改:

class ChartView : public QChartView {
    qreal mFactor=1.0;
protected:
    void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE
    {
        chart()->zoomReset();

        mFactor *= event->angleDelta().y() > 0 ? 0.5 : 2;

        QRectF rect = chart()->plotArea();
        QPointF c = chart()->plotArea().center();
        rect.setWidth(mFactor*rect.width());
        rect.moveCenter(c);
        chart()->zoomIn(rect);

        QChartView::wheelEvent(event);
    }
};

我使用以下代碼對x和y縮放都起作用了:

void wheelEvent(QWheelEvent *event){
qreal factor;
if ( event->delta() > 0 )
    factor = 2.0;
else
    factor = 0.5;

QRectF r = QRectF(chart()->plotArea().left(),chart()->plotArea().top(),
                                    chart()->plotArea().width()/factor,chart()->plotArea().height()/factor);
QPointF mousePos = mapFromGlobal(QCursor::pos());
r.moveCenter(mousePos);
chart()->zoomIn(r);
QPointF delta = chart()->plotArea().center() -mousePos;
chart()->scroll(delta.x(),-delta.y());}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM