在paintEvent中警告QPainter

时间:2018-08-17 22:36:46

标签: c++ qt qt5 qpainter qchartview

我试图在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,但是我犯了同样的错误

1 个答案:

答案 0 :(得分:1)

请勿使用您的 QChartView 子类,而应使用其视口。

QChartView来自QGraphicsView,而QAbstractScrollArea又来自this answer并根据documentation(以及那里引用的source of QGraphicsView),您应该将视口用作您的 QPainter 的绘画设备,而不是小部件本身。

所以,而不是

QPainter painter(this);

QPainter painter(viewport());

在{{3}}中也可以看到相同的内容,即:

// Set up the painter
QPainter painter(viewport());