一、前言:
推荐阅读内容
https://www.cnblogs.com/swarmbees/p/6058263.html
https://www.cnblogs.com/xiongxuanwen/p/10102301.html
以及官方文档
二、正文
//新建一个标签
m_label = new QCPItemText(m_plot);
m_label->setClipToAxisRect(false);
m_label->setPadding(QMargins(5, 5, 5, 5));
m_label->setBrush(QBrush(Qt::NoBrush));
m_label->setPen(QPen(QColor(Qt::red)));
m_label->setFont(QFont("Arial", 8));
m_label->setColor(Qt::black);
m_label->setText("Test");
m_label->setPositionAlignment(Qt::AlignLeft | Qt::AlignVCenter);
m_label->setSelectedBrush(QBrush(Qt::green));
//使能可选中
m_label->setSelectable(true);
//使能可选中,这里 QCP::iSelectItems 可以令像 Text/Line 这类控件能够被选中
m_customplot->setInteractions(QCP::iSelectItems);
//选中之后可以这个函数获取选中项
m_customplot->selectedItems();
//重新实例化鼠标事件
void QCustomLine::mousePressEvent(QMouseEvent *event)
{
QCustomPlot::mousePressEvent(event);
//默认设置同时只能选中一个,所以选取第一个对象
if (m_customplot->selectedItems().isEmpty())
return;
temp_selected = dynamic_cast<QCPItemText*>(m_customplot->
selectedItems().value(0);
}
void QCustomLine::mouseMoveEvent(QMouseEvent *event)
{
routeMouseEvents(event);
// 选中时候移动
if (temp_selected) {
temp_selected->setCoords(m_customplot->xAxis->pixelToCoord(event->x()),
m_customplot->yAxis->pixelToCoord(event->y()));
m_customplot->replot();
}
}
void QCustomLine::mouseReleaseEvent(QMouseEvent *event)
{
routeMouseEvents(event);
temp_selected = nullptr;
qDebug() << "----released!";
}