2

我试图在 QChartView 中绘制更多信息,所以我重新实现了paintEvent

  virtual void paintEvent(QPaintEvent *event) {
    QChartView::paintEvent(event);
    OmenChart *mchr = dynamic_cast<OmenChart *>(this->chart());
    if(mchr == nullptr)
        return;
    QPainter painter(this);

    const int labelOffset = 2 + 2;
    painter.setFont(this->font());
    painter.setPen(QPen(Qt::black));
    QFontMetrics fm(painter.font());


    const OmenScatterSeries *omnSr = mchr->serie();
    QVector<QPointF> points = omnSr->pointsVector();
    QStringList labels = omnSr->pointLabels();

    for (int i(0); i < labels.count(); i++) {
        QString pointLabel = labels[i];

        // Position text in relation to the point
        int pointLabelWidth = fm.width(pointLabel);
        QPointF position(points.at(i));
        position.setX(position.x() - pointLabelWidth / 2);
        position.setY(position.y() - labelOffset);
        painter.drawText(position, pointLabel);
    }
}

我正在接受这些错误

QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setFont: Painter not active
QPainter::setPen: Painter not active
QPainter::font: Painter not active
QWidget::paintEngine: Should no longer be called

对此有什么想法吗?我也使用了painter.begin 和end 但我犯了同样的错误

4

1 回答 1

6

不要在QChartView的子类上绘制,而是在其视口上绘制。

QChartView派生自QGraphicsView,后者又派生自QAbstractScrollArea,根据此答案(以及引用的文档),您应该将视口用作QPainter的绘画设备,而不是小部件本身。

所以,而不是

QPainter painter(this);

QPainter painter(viewport());

在QGraphicsView的源代码中也可以看到相同的内容,即:

// Set up the painter
QPainter painter(viewport());
于 2018-08-18T01:49:38.997 回答