我正在创建使用 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->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?