The principle is to obtain the clicked coordinate point through the mouse event, and then through a series of transformations to obtain the coordinate value:
1. Define the mouse event slot function in the header file:
private slots:
void slot_mouseRelese(QMouseEvent*);
2. Define the signal slot in the source file:
//Qcustomplot鼠标事件信号槽
connect(ui->customplot, SIGNAL(mouseRelease(QMouseEvent*)),this, SLOT(slot_mouseRelese(QMouseEvent*)));
3. In the initialization function of Qcustomplot, determine the precision of the mouse click:
ui->customplot->setSelectionTolerance(1);
4. Write the slot function:
//排除非左鼠标键
if (event->button() != Qt::LeftButton){ return; }
//获取点击的点坐标
QPointF ChickedPoint = event->pos();
//排除区间外鼠标点
if(!ui->customplot->viewport().contains(event->pos())){return;}
//将像素坐标转换为轴值
double currentx = ui->customplot->xAxis->pixelToCoord(ChickedPoint.x());
double currenty = ui->customplot->yAxis->pixelToCoord(ChickedPoint.y());
//使用QToolTip输出值,
QToolTip::showText(mapToGlobal(event->pos()),QString("当前点值为:%1").arg(currenty),this);
It should be noted that: QToolTip::showText
the function prototype of the function takes the first parameter as the global coordinate. When the window is not full screen, it will cause trouble (the output information of QToolTip may be outside the window), and event->pos()
the clicked point is obtained in the window. The coordinates in the body, not the coordinates in the entire screen, for example, if the point with the coordinates (0,0) of the form is clicked, QToolTip::showText
the output information will appear in the upper left corner of the screen instead of the upper left corner of the window. Therefore, we need a function mapToGlobal
to convert the clicked window coordinates to global coordinates. (If the form has a parent form, you also need to use mapToParent()
to convert the form coordinates to the parent form coordinates and then convert them to global coordinates)