I'm trying to draw a point where I click on a QChart. To do so I've created a "ChartWidget" class that inherits QChart and overrided the paint method like this :
void ChartWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QtCharts::QChart::paint(painter, option, widget);
if (_pointToDraw != nullptr)
{
std::cout << "Drawing point" << std::endl;
QPen pen;
pen.setColor(QColor(255, 0, 0, 255));
pen.setWidth(3);
painter->setPen(pen);
painter->drawPoint(*_pointToDraw);
delete _pointToDraw;
_pointToDraw = nullptr;
}
}
void ChartWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
std::cout << "Clicked at " << event->pos().x() << "/" << event->pos().y() << std::endl;
_pointToDraw = new QPointF(event->pos());
update();
}
It seems that the point is drawn but behind the chart because I can only see it when I click just outside of the chart, like in this screenshot :
If I click in the middle of the chart nothing is visibly drawn.
Any idea of what I am doing wrong and how I can fix this ?
As you point out QChart only draws the background, the main function of QChart is to save the configuration of the drawing as the theme, the type of chart, etc. So you can not show the button. A workaround is to create a QGraphicsEllipseItem:
class ChartWidget: public QChart
{
public:
ChartWidget(QGraphicsItem *parent = nullptr, Qt::WindowFlags wFlags = Qt::WindowFlags()):
QChart(parent, wFlags), item(new QGraphicsEllipseItem(QRectF(-3, -3, 6, 6)))
{
const QColor color(255, 0, 0, 255);
item->setZValue(100);
QPen pen(color);
pen.setWidth(3);
item->setBrush(color);
item->setPen(pen);
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(!item->scene()) scene()->addItem(item);
item->setPos(event->scenePos());
QChart::mousePressEvent(event);
}
private:
QGraphicsEllipseItem *item;
};