1

QChartをクリックしたポイントを描画しようとしています。そのために、QChart を継承する「ChartWidget」クラスを作成し、次のようにペイント メソッドをオーバーライドしました。

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();
}

このスクリーンショットのように、チャートのすぐ外側をクリックしたときにしか表示されないため、ポイントは描画されているように見えますが、チャートの後ろにあります。

スクリーンショット

チャートの中央をクリックすると、何も表示されません。

私が間違っていることと、これを修正する方法について何か考えはありますか?

4

1 に答える 1

1

ご指摘のとおり、QChart は背景のみを描画します。QChart の主な機能は、描画の構成をテーマ、グラフの種類などとして保存することです。したがって、ボタンを表示することはできません。回避策は、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;
};
于 2019-02-20T01:05:10.457 に答える