Qwt Plot开发:如何基于鼠标光标实现缩放功能?
QwtPlotMagnifier: Zoom Relative to Mouse Cursor Position
Got it, let's fix this—by default QwtPlotMagnifier zooms around the plot center, but it's straightforward to modify it to zoom relative to where your mouse is pointing. Here's a step-by-step solution:
1. Create a Custom Magnifier Class
We'll subclass QwtPlotMagnifier and override the rescale method to implement cursor-centered zoom logic:
#include <QwtPlotMagnifier> #include <QwtPlot> #include <QwtScaleMap> #include <QCursor> class CursorCenteredMagnifier : public QwtPlotMagnifier { public: explicit CursorCenteredMagnifier(QWidget* canvas) : QwtPlotMagnifier(canvas) {} protected: void rescale(double factor) override { QwtPlot* plot = this->plot(); if (!plot) return; // Get mouse position relative to the plot canvas QPoint mouseCanvasPos = canvas()->mapFromGlobal(QCursor::pos()); // Fall back to default center zoom if mouse is outside the canvas if (!canvas()->rect().contains(mouseCanvasPos)) { QwtPlotMagnifier::rescale(factor); return; } // Convert screen coordinates to plot data coordinates QwtScaleMap xMap = plot->canvasMap(QwtPlot::xBottom); QwtScaleMap yMap = plot->canvasMap(QwtPlot::yLeft); double mouseDataX = xMap.invTransform(mouseCanvasPos.x()); double mouseDataY = yMap.invTransform(mouseCanvasPos.y()); // Grab current axis ranges const QwtScaleDiv& xDiv = plot->axisScaleDiv(QwtPlot::xBottom); const QwtScaleDiv& yDiv = plot->axisScaleDiv(QwtPlot::yLeft); double xMin = xDiv.lowerBound(); double xMax = xDiv.upperBound(); double yMin = yDiv.lowerBound(); double yMax = yDiv.upperBound(); // Calculate new ranges: keep the mouse's data point fixed on screen double newXMin = mouseDataX - (mouseDataX - xMin) * factor; double newXMax = mouseDataX + (xMax - mouseDataX) * factor; double newYMin = mouseDataY - (mouseDataY - yMin) * factor; double newYMax = mouseDataY + (yMax - mouseDataY) * factor; // Apply the new scale to the plot plot->setAxisScale(QwtPlot::xBottom, newXMin, newXMax); plot->setAxisScale(QwtPlot::yLeft, newYMin, newYMax); } };
2. Replace the Default Magnifier
In your plot initialization code, swap out the default magnifier with our custom one:
// Remove the default magnifier (if it was automatically created) delete ui->plot->magnifier(); // Install our cursor-centered magnifier new CursorCenteredMagnifier(ui->plot->canvas());
Key Details to Note
- Axis Support: This example uses
xBottomandyLeftaxes. If your plot uses other axes (likexToporyRight), adjust the axis enum values in the code. - Mouse Outside Canvas: We added a check to fall back to the default center zoom if the mouse is outside the plot canvas—this is a nice usability touch.
- Zoom Factor: The default wheel zoom factor is 2.0 (zoom in) and 0.5 (zoom out). You can adjust this with
setWheelFactor(double factor)on your magnifier instance. - Qwt Version: This code works with Qwt 6.x (the most widely used stable branch).
内容的提问来源于stack exchange,提问作者Süleyman Kabadayı
相关产品推荐
相关产品推荐

