I am creating widget classes that draw grids using QWidgets paint event. My base class BaseRenderArea contains this method:
//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);
}
I am calling this method from the paintEvent of the derived class widget.
//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);
}
The drawGuesses method in the derived class is implemented as follows:
//draws the guesses made until this moment
void DebugRenderArea::drawGuesses(QPainter *painter)
{
QList <GuessPoint> list = m_logic->getListGuesses();
BaseRenderArea::drawGuesses(list,painter);
}
This approach gives me a segmentation fault in the BaseRenderArea::drawGuesses in the second line painter->setPen....
If I change the BaseRenderArea::drawGuesses with the following code (not reusing the QPainter created in the derived class but creating a new 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);
}
everything works fine. My questions why ? What can I do to use the QPainter created in the paintEvent of the derived class in method of the base class?
The documentation says that you can't have 2 active QPainter
s on the same paint device.
So, because BaseRenderArea::paintEvent
is probably creating its own QPainter
, it might have invalidated the one you created before in DebugRenderArea::paintEvent
.
You could simply reorder the two lines:
BaseRenderArea::paintEvent(event);
QPainter painter(this);