0

我对 Qt 和 C++ 很陌生。我有一个 QChart,它有一个 QLineSeries 对象。我想向用户展示鼠标在坐标系上的投影。我的问题是我可以在除 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 Callout Example 那样编辑我的代码。
我得到的错误:'virtual void QChart_ME::mouseMoveEvent(QGraphicsSceneMouseEvent*)' 在此上下文中受到保护 this->chartTrendLine->mouseMoveEvent(myEvent);

我该如何解决这个问题?

4

1 回答 1

0

原因

您正在为您的boxWhiskerDialog班级而不是为QChart.

解决方案

子类化QChart并重新实现它mouseMoveEvent,而不是重新实现boxWhiskerDialog::mouseMoveEvent

于 2020-10-27T11:15:03.453 回答