84 lines
2.3 KiB
C++
84 lines
2.3 KiB
C++
|
|
#include "localcustomplot.h"
|
||
|
|
|
||
|
|
LocalCustomPlot::LocalCustomPlot(QWidget *parent)
|
||
|
|
: QCustomPlot(parent)
|
||
|
|
{
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
// 鼠标按下事件
|
||
|
|
void LocalCustomPlot::mousePressEvent(QMouseEvent *event)
|
||
|
|
{
|
||
|
|
// 先取消所有选中的项
|
||
|
|
for (auto* item : selectedItems())
|
||
|
|
{
|
||
|
|
item->setSelected(false);
|
||
|
|
}
|
||
|
|
|
||
|
|
for(int i = 0; i < itemCount();i++)
|
||
|
|
{
|
||
|
|
if (QCPItemText* textItem = qobject_cast<QCPItemText*>(item(i)))
|
||
|
|
{
|
||
|
|
QRectF rect = getTextBoundingRect(textItem);
|
||
|
|
if(rect.contains(event->pos()))
|
||
|
|
{
|
||
|
|
_draggedTextItem = textItem;
|
||
|
|
_draggedTextItem->setSelected(true); // 手动选择这个项
|
||
|
|
_lastMousePos = event->pos();
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
QCustomPlot::mousePressEvent(event);
|
||
|
|
}
|
||
|
|
|
||
|
|
// 鼠标释放事件
|
||
|
|
void LocalCustomPlot::mouseReleaseEvent(QMouseEvent *event)
|
||
|
|
{
|
||
|
|
_draggedTextItem = nullptr; // 清除拖动状态
|
||
|
|
|
||
|
|
QCustomPlot::mouseReleaseEvent(event);
|
||
|
|
}
|
||
|
|
|
||
|
|
// 鼠标移动事件
|
||
|
|
void LocalCustomPlot::mouseMoveEvent(QMouseEvent *event)
|
||
|
|
{
|
||
|
|
if (_draggedTextItem)
|
||
|
|
{
|
||
|
|
double dx = event->pos().x() - _lastMousePos.x();
|
||
|
|
double dy = event->pos().y() - _lastMousePos.y();
|
||
|
|
|
||
|
|
_draggedTextItem->position->setType(QCPItemPosition::ptAbsolute); // 使用屏幕坐标系
|
||
|
|
_draggedTextItem->position->setCoords(
|
||
|
|
_draggedTextItem->position->key() + dx,
|
||
|
|
_draggedTextItem->position->value() + dy
|
||
|
|
);
|
||
|
|
|
||
|
|
_lastMousePos = event->pos();
|
||
|
|
replot(); // 刷新图表
|
||
|
|
}else{
|
||
|
|
QCustomPlot::mouseMoveEvent(event);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
QRectF LocalCustomPlot::getTextBoundingRect(QCPItemText* textItem) {
|
||
|
|
textItem->position->setType(QCPItemPosition::ptAbsolute); // 使用屏幕坐标系
|
||
|
|
// 获取文本的字体
|
||
|
|
QFont font = textItem->font();
|
||
|
|
|
||
|
|
// 使用 QFontMetrics 获取字体的尺寸
|
||
|
|
QFontMetrics fontMetrics(font);
|
||
|
|
|
||
|
|
// 获取文本的矩形边界
|
||
|
|
QRectF textRect = fontMetrics.boundingRect(textItem->text());
|
||
|
|
|
||
|
|
// 获取文本框的位置
|
||
|
|
QPointF textPosition = textItem->position->coords();
|
||
|
|
|
||
|
|
// 设置文本矩形的位置,将其居中到文本框的实际位置
|
||
|
|
textRect.moveCenter(textPosition.toPoint());
|
||
|
|
|
||
|
|
return textRect;
|
||
|
|
}
|