如何使用QMouseEvent在QChart中显示鼠标位置?

问题描述

我在Qt和C ++上还很陌生。我有一个具有QLineSeries对象的QChart。我想向用户展示鼠标在坐标系上的投影。我的问题是我可以在除QChart对象之外的任何地方显示坐标。我只想将鼠标放在QChart上才能显示坐标。这是我的代码示例:

boxWhisker.h文件

QGraphicsSimpleTextItem *m_coordX;
QGraphicsSimpleTextItem *m_coordY;
QChart *chartTrendLine;
QChartView *trendLineChartView;
QLineSeries *trendLine;

boxWhisker.cpp文件

this->chartTrendLine = new QChart();
this->chartTrendLine->addSeries(this->trendLine);
this->chartTrendLine->legend()->setVisible(true);
this->chartTrendLine->createDefaultAxes();
this->chartTrendLine->setAcceptHoverEvents(true);

this->trendLineChartView = new QChartView(this->chartTrendLine);
this->trendLineChartView->setRenderHint(QPainter::Antialiasing);

this->m_coordX = new QGraphicsSimpleTextItem(this->chartTrendLine);
this->m_coordX->setPos(this->chartTrendLine->size().width()/2+50,this->chartTrendLine->size().height());

this->m_coordY = new QGraphicsSimpleTextItem(this->chartTrendLine);
this->m_coordY->setPos(this->chartTrendLine->size().width()/2+100,this->chartTrendLine->size().height());

void boxWhiskerDialog::mouseMoveEvent(QMouseEvent *mouseEvent)
{
this->m_coordY->setText(QString("Y: %1").arg(this->chartTrendLine->mapToValue(mouseEvent->pos()).y()));
this->m_coordX->setText(QString("X: %1").arg(this->chartTrendLine->mapToValue(mouseEvent->pos()).x()));
}

我的问题是如何仅在QChart上显示坐标?任何帮助将不胜感激!

编辑

在这里,我尝试创建一个由QChart类继承的新类,并在新类中定义mouseEvent函数。这是我的代码示例:

qchart_me.h:

class QChart_ME : public QT_CHARTS_NAMESPACE::QChart
{
public:
    QChart_ME();

protected:
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);

private:
    QGraphicsSimpleTextItem *m_coordX;
    QGraphicsSimpleTextItem *m_coordY;
    QChart *m_chart;

};

qchart_me.cpp:

QChart_ME::QChart_ME()
{

}

void QChart_ME::mouseMoveEvent(QGraphicsSceneMouseEvent *Myevent)
{
    m_coordX->setText(QString("X: %1").arg(m_chart->mapToValue(Myevent->pos()).x()));
    m_coordY->setText(QString("Y: %1").arg(m_chart->mapToValue(Myevent->pos()).y()));

}

boxWhisker.h:

QChart_ME *chartTrendLine; 

boxWhisker.cpp

this->chartTrendLine = new QChart_ME();
this->chartTrendLine->addSeries(this->trendLine);
this->chartTrendLine->legend()->setVisible(true);
this->chartTrendLine->createDefaultAxes();
this->chartTrendLine->setAcceptHoverEvents(true);

QGraphicsSceneMouseEvent *myEvent;

this->chartTrendLine->mouseMoveEvent(myEvent);

我试图编辑我的代码,例如Qt标注示例。
我得到的错误: 在此上下文中保护了'virtual void QChart_ME :: mouseMoveEvent(QGraphicsSceneMouseEvent *)' this-> chartTrendLine-> mouseMoveEvent(myEvent);

我该如何解决这个问题?

解决方法

原因

您正在为Error: Process 'docker exec -i "myapp...' exited with code 1 Error: Error: No such container: myapp 类而不是boxWhiskerDialog获得鼠标事件。

解决方案

子类QChart并重新实现其QChart,而不是重新实现mouseMoveEvent

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...