In questa pagina

Esempio di linea di zoom

L'esempio mostra come creare un effetto di zoom personalizzato.

L'esempio illustra come creare un effetto di zoom personalizzato con QRubberBand utilizzando il mouse e come utilizzare i gesti tattili per la panoramica e lo zoom.

Screenshot che mostra un esempio di grafico a onde

Screenshot del grafico a onde ingrandito

Esecuzione dell'esempio

È possibile eseguire l'esempio da:

Personalizzazione degli effetti di zoom

Creiamo innanzitutto una serie di linee con alcuni dati di esempio.

    auto series = new QLineSeries;
    for (int i = 0; i < 500; i++) {
        QPointF p((qreal) i, qSin(M_PI / 50 * i) * 100);
        p.ry() += QRandomGenerator::global()->bounded(20);
        *series << p;
    }

Quindi creiamo una vista grafico personalizzata derivando da `QChartView`:

class ChartView : public QChartView

Sovrascriviamo la gestione degli eventi del mouse e dei tasti

protected:
    bool viewportEvent(QEvent *event);
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);
    void keyPressEvent(QKeyEvent *event);

Quindi implementiamo una logica personalizzata per gli eventi del mouse e dei tasti. Ad esempio, premendo il tasto '+' si ingrandisce l'immagine, mentre premendo il tasto '-' la si rimpicciolisce.

void ChartView::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Plus:
        chart()->zoomIn();
        break;
    case Qt::Key_Minus:
        chart()->zoomOut();
        break;

Creiamo anche il nostro QChart:

class Chart : public QChart

Dove possiamo gestire i gesti:

bool Chart::sceneEvent(QEvent *event)
{
    if (event->type() == QEvent::Gesture)
        return gestureEvent(static_cast<QGestureEvent *>(event));
    return QChart::event(event);
}

bool Chart::gestureEvent(QGestureEvent *event)
{
    if (QGesture *gesture = event->gesture(Qt::PanGesture)) {
        auto pan = static_cast<QPanGesture *>(gesture);
        QChart::scroll(-(pan->delta().x()), pan->delta().y());
    }

    if (QGesture *gesture = event->gesture(Qt::PinchGesture)) {
        auto pinch = static_cast<QPinchGesture *>(gesture);
        if (pinch->changeFlags() & QPinchGesture::ScaleFactorChanged)
            QChart::zoom(pinch->scaleFactor());
    }

    return true;
}

Si noti che sarà necessario chiamare la funzione `grabGesture()` sia per ` QMainWindow ` che per `QChart`.

Progetto di esempio su code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.