缩放线条示例
本示例演示了如何创建自定义缩放效果。
本示例演示了如何通过QRubberBand 结合鼠标操作来创建自定义缩放效果,以及如何使用触控手势进行平移和缩放。


运行示例
您可以通过以下方式运行该示例:
- Qt Creator
打开Welcome 模式,并从Examples 中选择该示例。有关更多信息,请参阅Qt Creator :教程:构建和运行。
- Qt Extension for Visual Studio Code
在Command Palette 中运行Qt: Open Qt examples 命令,然后从列表中选择该示例。有关更多信息,请参阅Qt Extension for Visual Studio Code :教程:构建和运行。
自定义缩放效果
首先,我们使用一些示例数据创建一个折线系列。
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;
}然后,我们通过继承 QChartView 来创建一个自定义图表视图:
class ChartView : public QChartView我们重写鼠标和键盘事件处理
protected:
bool viewportEvent(QEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void keyPressEvent(QKeyEvent *event);接着,为鼠标和键盘事件实现自定义逻辑。例如,按下“+”键将放大,按下“-”键将缩小。
void ChartView::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Plus:
chart()->zoomIn();
break;
case Qt::Key_Minus:
chart()->zoomOut();
break;我们还创建了自己的 QChart:
class Chart : public QChart在此处我们可以处理手势:
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;
}请注意,您需要同时在QMainWindow 和QChart中调用grabGesture()。
© 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.