在基类中访问QPainter

时间:2012-12-15 23:09:50

标签: qt qpainter

我正在创建使用QWidgets绘制事件绘制网格的窗口小部件类。我的基类BaseRenderArea包含这个方法:

//draws a list of guesses in the grid
void BaseRenderArea::drawGuesses(const QList <GuessPoint> &list, QPainter *painter)
{
    //QPainter painter1(this);

    QPen currentPen = painter->pen();

    painter->setPen(QString("red"));

    for(int i=0;i<list.size();i++)
    {
        GuessPoint gp = list.at(i);

        switch(gp.m_type)
        {
        case GuessPoint::Miss:
            drawMiss(gp.m_row, gp.m_col, painter);
            break;
        case GuessPoint::Dead:
            drawDead(gp.m_row, gp.m_col, painter);
            break;
        case GuessPoint::Hit:
            drawHit(gp.m_row, gp.m_col, painter);
            break;
        default:
            ;
        }
    }

    painter->setPen(currentPen);

}

我从派生类窗口小部件的paintEvent调用此方法。

//the paint event
//uses the base class to draw the texts and
//the grid
//and then draws the guesses made until now
//as well as the score for each choice of the computer
void DebugRenderArea::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    BaseRenderArea::paintEvent(event);

    //to do: draw guesses
    drawGuesses(&painter);

    //draw scores
    //drawScores(&painter);

}

派生类中的drawGuesses方法实现如下:

//draws the guesses made until this moment
void DebugRenderArea::drawGuesses(QPainter *painter)
{
    QList <GuessPoint> list = m_logic->getListGuesses();
    BaseRenderArea::drawGuesses(list,painter);

}

这种方法在第二行painter-&gt; setPen ....中的BaseRenderArea :: drawGuesses中给出了一个分段错误。

如果我使用以下代码更改BaseRenderArea :: drawGuesses(不重用派生类中创建的QPainter但创建新的QPainter):

//draws a list of guesses in the grid
void BaseRenderArea::drawGuesses(const QList <GuessPoint> &list, QPainter *painter)
{
    QPainter painter1(this);

    QPen currentPen = painter1.pen();

    painter1.setPen(QString("red"));

    for(int i=0;i<list.size();i++)
    {
        GuessPoint gp = list.at(i);

        switch(gp.m_type)
        {
        case GuessPoint::Miss:
            drawMiss(gp.m_row, gp.m_col, &painter1);
            break;
        case GuessPoint::Dead:
            drawDead(gp.m_row, gp.m_col, &painter1);
            break;
        case GuessPoint::Hit:
            drawHit(gp.m_row, gp.m_col, &painter1);
            break;
        default:
            ;
        }
    }

    painter1.setPen(currentPen);

}
一切正常。我的问题为什么?如何在基类的方法中使用派生类的paintEvent中创建的QPainter?

1 个答案:

答案 0 :(得分:0)

documentation表示您在同一个绘图设备上不能有2个活动QPainter

因此,由于BaseRenderArea::paintEvent可能正在创建自己的QPainter,因此它可能会使之前在DebugRenderArea::paintEvent中创建的那个无效。

你可以简单地重新排序这两行:

BaseRenderArea::paintEvent(event);

QPainter painter(this);