2012-12-15 51 views
1

我正在創建使用QWidgets繪製事件繪製網格的窗口小部件類。我的基類BaseRenderArea包含此方法:訪問基類中的QPainter

//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); 

} 

這種方法使我在BaseRenderArea分段故障:: drawGuesses在第二行painter-> setPen ... 。

如果我改變BaseRenderArea ::下面的代碼(不重用在派生類中創建的QPainter的是創造一個新的QPainter)drawGuesses:

//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?

+0

setpen()應該得到的QColor作爲參數,你不應該寫的Qt ::紅色代替的QString(「紅」)? 在第一種情況下,您通過爲QPainter提供對DebugRenderArea實例的引用來初始化QPainter,並且在第二種情況下對BaseRenderArea實例的引用是您想要的嗎? –

+0

該代碼也適用於QString(「紅色」)。在這種情況下,我認爲除了有一次QPainter是在基類中創建的,而另一次是在派生類中創建的,還有一個相同的對象。我不知道這應該怎麼做。你有什麼建議嗎? – Cristi

回答

0

documentation表示在同一個噴漆設備上不能有兩個活動的QPainter s。

因此,因爲BaseRenderArea::paintEvent可能是自己創建的QPainter,所以它可能會使您之前在DebugRenderArea::paintEvent中創建的那個無效。

你可以簡單地重新排列兩行:

BaseRenderArea::paintEvent(event); 

QPainter painter(this); 
+0

謝謝。這確實有效。所以Qt知道在BaseRenderArea :: paintEvent中創建的QPainter和在DebugRenderArea :: paintEvent中創建的QPainter引用了相同的widget- – Cristi