1、拖動區域放大?
在 QCustomPlot 中實現 ?拖動區域放大?(即通過鼠標左鍵拖動繪制矩形框選區域進行放大)的核心方法是設置?SelectionRectMode
。具體操作步驟:
1?)禁用拖動模式?
確保先關閉默認的圖表拖動功能(否則會沖突)。
customPlot->setInteraction(QCP::iRangeDrag, false); // 關閉拖動
2?)啟用框選放大模式?
設置選擇矩形模式為?srmZoom。
customPlot->setSelectionRectMode(QCP::SelectionRectMode::srmZoom); // 啟用框選放大
3)視覺效果定制(可選)?
可自定義選框的邊框和填充顏色。
customPlot->selectionRect()->setPen(QPen(Qt::black, 1, Qt::DashLine)); // 虛線邊框
customPlot->selectionRect()->setBrush(QBrush(QColor(0,0,100,50))); // 半透明藍色填充
?注意:拖拽與框選模式互斥?
拖動 (iRangeDrag
) 與框選放大 (srmZoom
) ?無法同時生效?。若需切換功能(如右鍵拖動、左鍵框選),需自定義鼠標事件處理邏輯 。
2、?恢復原始視圖
添加按鈕或快捷鍵調用?rescaleAxes()
?可一鍵重置坐標軸顯示范圍。或通過?setRange
?手動重置坐標軸范圍。
右鍵點擊回到未放大狀態?(撤銷縮放操作)的功能,可以通過以下兩種方式實現。
1)方式一:使用內置復位按鈕(推薦簡單場景)
添加復位按鈕?
創建按鈕觸發?rescaleAxes()
?恢復初始視圖:
customPlot->rescaleAxes(); // 自動重置坐標軸范圍customPlot->replot(); // 重繪圖表
右鍵菜單集成復位選項?
在右鍵菜單中添加"復位"選項:
void MyCustomPlot::contextMenuEvent(QContextMenuEvent *event) {QMenu menu(this);QAction *resetAction = menu.addAction("復位");connect(resetAction, &QAction::triggered, this, &MyCustomPlot::onResetZoom);menu.exec(event->globalPos());
}void MyCustomPlot::onResetZoom() {rescaleAxes();replot();
}
2)方式二:縮放歷史棧
適用于需要逐步撤銷多次縮放操作的場景:
2.1)定義歷史記錄棧
QStack<QPair<QCPRange, QCPRange>> zoomHistory; // 存儲(x軸范圍, y軸范圍)
2.2)保存縮放前的狀態?
在縮放操作前保存當前坐標軸范圍:
void MyCustomPlot::beforeZoom() {zoomHistory.push(qMakePair(xAxis->range(), yAxis->range()));
}
?2.3)右鍵觸發撤銷操作
void MyCustomPlot::mousePressEvent(QMouseEvent *event) {if (event->button() == Qt::RightButton && !zoomHistory.isEmpty()) {QPair<QCPRange, QCPRange> prevRange = zoomHistory.pop();xAxis->setRange(prevRange.first); // 恢復x軸yAxis->setRange(prevRange.second); // 恢復y軸replot();}QCustomPlot::mousePressEvent(event);
}