You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nmWTAI-Platform/Src/nmNum/nmPlot/nmPlotView.cpp

418 lines
14 KiB
C++

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <QMenu>
//#include <QFileDialog>
#include "ZxBaseUtil.h"
#include "zxLogInstance.h"
#include "ZxPaintParam.h"
#include "ZxSubAxisX.h"
#include "ZxSubAxisY.h"
#include "nmPlotScene.h"
#include "nmPlotView.h"
#include "nmObjToolBase.h"
#include <QApplication>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QFontMetricsF>
#include <QLocale>
#include <QPainter>
#include <QPainterPath>
#include <QtCore/qnumeric.h>
#include <cmath>
ZX_DEFINE_DYNAMIC(mPlotView, nmPlotView)
nmPlotView::nmPlotView()
: m_scaleBarVisible(true), m_mapHistoryLocked(false)
{
// 未按下鼠标时也接收视口移动事件,实时更新模型位置。
viewport()->setMouseTracking(true);
connect(&m_mapHistories, SIGNAL(canUndoChanged(bool)), this, SLOT(updateMapHistoryAvailability()));
connect(&m_mapHistories, SIGNAL(canRedoChanged(bool)), this, SLOT(updateMapHistoryAvailability()));
}
void nmPlotView::setScaleBarVisible(bool visible)
{
if (m_scaleBarVisible == visible) return;
m_scaleBarVisible = visible;
updateViewport();
}
void nmPlotView::paintOverlay(QPainter* painter)
{
tCurvePlotView::paintOverlay(painter);
if (!m_scaleBarVisible) return;
const nmPlotScene* plotScene = dynamic_cast<const nmPlotScene*>(getScene());
if (plotScene == nullptr || plotScene->m_pPlot == nullptr) return;
ZxPlot* plot = plotScene->m_pPlot;
const ZxSubAxisX* axis = plot->getMainAxisX();
if (axis == nullptr) return;
const QRectF area = mapFromScene(plot->getInnerRectF())
.intersected(QRectF(viewport()->rect()));
const qreal margin = 10.0;
const qreal tickHeight = 5.0;
const qreal labelGap = 2.0;
const QFont labelFont = font();
const QFontMetricsF metrics(labelFont, painter->device());
const qreal maxWidth = qMin(qreal(120.0), area.width() - 4.0 * margin);
if (maxWidth < 24.0 || area.height() < 2.0 * margin + tickHeight + labelGap + metrics.height()) {
return;
}
// 按视口横向距离反算地图坐标,独立响应水平和竖直缩放。
const QPointF start = mapToScene(QPointF(area.left(), area.center().y()));
const QPointF end = mapToScene(QPointF(area.left() + maxWidth, area.center().y()));
const double maxDistance = qAbs(axis->getValueForPos(end.x()) - axis->getValueForPos(start.x()));
if (!qIsFinite(maxDistance) || maxDistance <= 0.0) return;
// 在可用宽度内取整齐的 1、2、5 倍十进制刻度。
const double decade = std::pow(10.0, std::floor(std::log10(maxDistance)));
if (!qIsFinite(decade) || decade <= 0.0) return;
const double leading = maxDistance / decade;
const double distance = decade * (leading >= 5.0 ? 5.0 : (leading >= 2.0 ? 2.0 : 1.0));
const qreal width = maxWidth * (distance / maxDistance);
const bool useKilometres = distance >= 1000.0;
const QString zero = QLatin1String("0");
const QString label = QLocale().toString(useKilometres ? distance / 1000.0 : distance, 'g', 6)
+ (useKilometres ? QLatin1String(" km") : QLatin1String(" m"));
const qreal startLabelWidth = metrics.width(zero);
const qreal endLabelWidth = metrics.width(label);
if (width < (startLabelWidth + endLabelWidth) / 2.0 + labelGap ||
width + (startLabelWidth + endLabelWidth) / 2.0 + 2.0 * margin > area.width()) {
return;
}
const qreal right = area.right() - margin - endLabelWidth / 2.0;
const qreal left = right - width;
const qreal bottom = area.bottom() - margin;
const qreal top = bottom - tickHeight;
QPainterPath bar;
bar.moveTo(left, top);
bar.lineTo(left, bottom);
bar.lineTo(right, bottom);
bar.lineTo(right, top);
const qreal baseline = top - labelGap - metrics.descent();
QPainterPath labels;
labels.addText(QPointF(left - startLabelWidth / 2.0, baseline), labelFont, zero);
labels.addText(QPointF(right - endLabelWidth / 2.0, baseline), labelFont, label);
// 用视口像素绘制,白色描边使刻度在底图和填充区上都能读清。
const QColor ink(32, 32, 32);
const QPen halo(QBrush(Qt::white), 3.0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
painter->save();
painter->resetTransform();
painter->setClipRect(area, Qt::IntersectClip);
painter->setRenderHint(QPainter::Antialiasing);
painter->strokePath(bar, halo);
painter->strokePath(bar, QPen(ink));
painter->strokePath(labels, halo);
painter->fillPath(labels, ink);
painter->restore();
}
void nmPlotView::setMapHistoryOwner(QObject* analysis)
{
QUndoStack* stack = m_analysisHistories.value(analysis, nullptr);
if (analysis != nullptr && stack == nullptr) {
stack = new QUndoStack(this);
m_analysisHistories.insert(analysis, stack);
m_mapHistories.addStack(stack);
connect(analysis, SIGNAL(destroyed(QObject*)), this, SLOT(removeMapHistory(QObject*)));
}
m_mapHistories.setActiveStack(stack);
}
void nmPlotView::removeMapHistory(QObject* analysis)
{
delete m_analysisHistories.take(analysis);
}
void nmPlotView::beginMapGeometryEditGroup()
{
Q_ASSERT(m_mapGeometryEditGroup.isNull());
m_mapGeometryEditGroup.reset(new QUndoCommand);
}
void nmPlotView::endMapGeometryEditGroup()
{
QScopedPointer<QUndoCommand> group(m_mapGeometryEditGroup.take());
QUndoStack* stack = mapEditHistory();
if (stack != nullptr && !group.isNull() && group->childCount() > 0) {
stack->push(group.take());
}
}
void nmPlotView::setMapHistoryLocked(bool locked)
{
if (m_mapHistoryLocked == locked) return;
m_mapHistoryLocked = locked;
updateMapHistoryAvailability();
}
bool nmPlotView::canReplayMapEdit(bool undo) const
{
return !m_mapHistoryLocked && (undo ? m_mapHistories.canUndo() : m_mapHistories.canRedo());
}
void nmPlotView::updateMapHistoryAvailability()
{
emit sigMapCanUndoChanged(canReplayMapEdit(true));
emit sigMapCanRedoChanged(canReplayMapEdit(false));
}
void nmPlotView::onPrepareContextMenu(QMenu* pMenu,
const QPointF& pos)
{
tCurvePlotView::onPrepareContextMenu(pMenu, pos);
// 框架已添加历史动作。按槽连接识别这两个动作,统一使用地图的回放状态。
foreach (QAction* action, pMenu->actions()) {
const bool undo = disconnect(action, SIGNAL(triggered()), this, SLOT(slotUndo()));
const char* historySlot = undo ? SLOT(slotUndo()) : SLOT(slotRedo());
if (!undo && !disconnect(action, SIGNAL(triggered()), this, historySlot)) {
continue;
}
connect(action, SIGNAL(triggered()), this, historySlot);
action->setText(undo ? tr("Undo") : tr("Redo"));
action->setEnabled(canReplayMapEdit(undo));
}
}
void nmPlotView::slotUndo()
{
emit sigMapHistoryActionRequested(QLatin1String("Undo"));
}
void nmPlotView::slotRedo()
{
emit sigMapHistoryActionRequested(QLatin1String("Redo"));
}
// 拖拽支持
void nmPlotView::dragEnterEvent(QDragEnterEvent *event)
{
m_bDraging = false;
emit sigCheckDragAccepted(event, m_bDraging);
if (m_bDraging)
{
event->accept();
}
}
void nmPlotView::dropEvent(QDropEvent *event)
{
if (m_bDraging)
{
m_bDraging = false;
emit sigDealwithDrop(event);
event->accept();
}
}
void nmPlotView::mouseMoveEvent(QMouseEvent* e)
{
ZxRenderView::mouseMoveEvent(e);
nmPlotScene* pScene = dynamic_cast<nmPlotScene*>(ZxRenderView::getScene());
if (nullptr == pScene || nullptr == pScene->m_pPlot)
{
return;
}
QPointF pos = mapToScene(QPoint(e->x(), e->y()));
ZxTempLayer* pTempLayer = pScene->getTempLayer();
if (nullptr != pTempLayer)
{
// 范围
QRectF rt = pScene->m_pPlot->getInnerRectF();
pTempLayer->setCrossLineRect(rt);
// 位置
pTempLayer->setCrossLinePos(pos);
// 文字
{
ZxSubAxisBase* pX = dynamic_cast<ZxSubAxisBase*>(pScene->m_pPlot->getMainAxisX());
ZxSubAxisBase* pY = dynamic_cast<ZxSubAxisBase*>(pScene->m_pPlot->getMainAxisY());
ZxSubAxisBase* pY2 = pScene->m_pPlot->getSysAxisY(AP_Right);
if (nullptr != pY2) //加入双Y轴的考虑
{
if (!pY2->isVisible() || pY2->isMinimizeAxis() || pY2 == pY)
pY2 = nullptr;
}
double dX = pX->getValueForPos(pos.x());
double dY = pY->getValueForPos(pos.y());
QString sValueX = ZxBaseUtil::getValidStr(dX, 3);
QString sValueY = ZxBaseUtil::getValidStr(dY, 3);
QString sValueY2 = "";
if (nullptr != pY2)//加入双Y轴的考虑
{
double dY2 = pY2->getValueForPos(pos.y());
sValueY2 = ZxBaseUtil::getValidStr(dY2, 3);
}
QString sTipsEx = "";
emit sigGetTipsExOfPos(sTipsEx, dX, dY); //此处不考虑双Y轴,TODO
// tips
QString s = QString("%1:%2 %3").arg(pX->getName()).arg(sValueX).arg(pX->getUnit());
s += ";";
if (!sTipsEx.isEmpty())
{
QPen pen = QPen(QColor(128, 128, 128));
pTempLayer->setCrossLinePen(pen);
pen.setWidthF(0.1);
s += sTipsEx;
}
else
{
pTempLayer->setCrossLinePen(QPen(QColor(192, 192, 192)));
s += QString("%1:%2 %3").arg(pY->getName()).arg(sValueY).arg(pY->getUnit());
if (!sValueY2.isEmpty() && nullptr != pY2)
s += QString(";%1:%2 %3").arg(pY2->getName()).arg(sValueY2).arg(pY2->getUnit());
}
pTempLayer->setTips(s);
// 状态栏
if (rt.contains(pos))
{
// 复用坐标轴换算结果,通知模型位置窗口刷新坐标。
emit sigPointerPos(dX, dY);
s = tr(" Current Pos:%1-%2").arg(sValueX).arg(sValueY);
if (!sValueY2.isEmpty())
s += QString("-%1").arg(sValueY2);
if (!sTipsEx.isEmpty())
{
s += " ";
s += sTipsEx;
}
if (!m_sCreationHint.isEmpty()) {
// 原因放在坐标前,避免状态栏较窄时看不到继续绘制的提示。
s = m_sCreationHint + " " + s;
}
}
else
{
s = "";
}
emit sigFresh2Status(s);
}
}
}
void nmPlotView::setCreationHint(const QString& hint)
{
if (m_sCreationHint == hint) {
return;
}
m_sCreationHint = hint;
// 双击检查失败后立即显示,不依赖下一次鼠标移动;沿用原有状态栏信号。
QString status = hint;
emit sigFresh2Status(status);
}
void nmPlotView::setCancellableTool(nmObjToolBase* tool)
{
m_cancellableTool = tool;
}
void nmPlotView::keyPressEvent(QKeyEvent* e)
{
const Qt::KeyboardModifiers modifiers = e->modifiers();
const bool undo = modifiers == Qt::ControlModifier;
const bool redo = modifiers == (Qt::ControlModifier | Qt::ShiftModifier);
if (e->key() == Qt::Key_Z && (undo || redo) && (hasFocus() || viewport()->hasFocus())) {
e->accept();
// 左键尚未松开时,历史命令可能移除本次鼠标交互引用的图元。
if (!QApplication::mouseButtons().testFlag(Qt::LeftButton)) {
emit sigMapHistoryActionRequested(undo ? QLatin1String("Undo") : QLatin1String("Redo"));
}
return;
}
if (m_cancellableTool && m_cancellableTool->getView() == this &&
m_cancellableTool->getRootTool() == getActiveTool()) {
if (e->key() == Qt::Key_Escape && m_cancellableTool->cancelInteraction()) {
// 创建取消可能同步移除工具;调用后只清理视图的弱引用,不再访问该工具。
m_cancellableTool = nullptr;
m_pendingCursorTool = nullptr;
e->accept();
return;
}
if (e->key() == Qt::Key_Backspace && e->modifiers() == Qt::NoModifier &&
m_cancellableTool->stepBackCreation(e->isAutoRepeat())) {
// 退点后保留工具登记,允许继续退点、重新选点或按 Esc 退出绘制。
e->accept();
return;
}
}
ZxRenderView::keyPressEvent(e);
}
void nmPlotView::requestHoverCursorRefresh(nmObjToolBase* tool)
{
m_pendingCursorTool = tool;
}
void nmPlotView::mouseReleaseEvent(QMouseEvent* e)
{
// 请求只在当前松手事件内有效;弱引用防止提交或同步槽销毁工具后仍访问它。
QPointer<ZxTool> rootTool = getActiveTool();
m_pendingCursorTool = nullptr;
ZxRenderView::mouseReleaseEvent(e);
QPointer<nmObjToolBase> objTool = m_pendingCursorTool;
m_pendingCursorTool = nullptr;
if (e->button() == Qt::LeftButton && e->buttons() == Qt::NoButton &&
rootTool && getActiveTool() == rootTool.data() && objTool &&
objTool->getView() == this && viewport()->rect().contains(e->pos())) {
// 只查询本次工具的悬停样式,不模拟移动,不重复提交坐标或触发吸附。
objTool->refreshHoverCursor(mapToScene(e->pos()));
}
}
void nmPlotView::focusOutEvent(QFocusEvent *e)
{
ZxRenderView::focusOutEvent(e);
nmPlotScene* pScene = dynamic_cast<nmPlotScene*>(ZxRenderView::getScene());
if (nullptr != pScene)
{
ZxTempLayer* pTempLayer = pScene->getTempLayer();
if (nullptr != pTempLayer)
{
pTempLayer->clearLineAndTips();
return;
}
}
}
void nmPlotView::leaveEvent(QEvent *e)
{
ZxRenderView::leaveEvent(e);
nmPlotScene* pScene = dynamic_cast<nmPlotScene*>(ZxRenderView::getScene());
if (nullptr != pScene)
{
ZxTempLayer* pTempLayer = pScene->getTempLayer();
if (nullptr != pTempLayer)
{
pTempLayer->clearLineAndTips();
// return;
}
}
QString s = "";
emit sigFresh2Status(s);
}