The problem with painting one widget inside another (parent)

I am trying to make a simple game under Qt 4.6. The idea is to have two widgets: one is the widget of the main window and represents the space, and the second is the starship widget inside the space (parent). The simplified code is as follows:

/*this is ship and child widget*/
class MyRect : public QWidget {

Q_OBJECT

public:
MyRect(QWidget* parent)
    : QWidget(parent)
{
    itsParent = parent;

    itsx = 120;
    itsy = 250;
    itsw = 110;
    itsh = 35;
    body = new QRect(itsx, itsy, itsw, itsh);

}

~MyRect() {}


protected:
    void paintEvent(QPaintEvent *event);

private:
int itsx;
int itsy;
int itsw;
int itsh;
QRect* body;
QWidget* itsParent;

};


void MyRect::paintEvent(QPaintEvent *event)
{

  QPen pen(Qt::black, 2, Qt::SolidLine);
  QColor hourColor(0, 255, 0);


  QPainter painter(itsParent);

  painter.setBrush(hourColor);  
  painter.setPen(pen);
  painter.drawRect(*body);

}


/*this is space and main window widget*/
class space : public QMainWindow
{
  Q_OBJECT

public:
    space(QWidget *parent = 0);
   ~space();

protected:


private:
   MyRect* ship;

};

space::space(QWidget *parent)
 : QMainWindow(parent)
{
   ship = new MyRect(this);
}

When I compile, the screen is blank and the rectangle is MyRect::bodynot drawn. I checked the Qt online documentation and did some google research with no luck. Any explanation in this regard is welcome. I want to draw one widget on another (parent).

+3
source share
1 answer

QPainter painter(itsParent); - . , . QPainter painter(this);
MyRect. . , MyRect::paintEvent() painter.drawRect(*body); painter.drawRect( rect() );
• , MyRect .
• : space::space()
  ship->move( 120, 250 );
  ship->resize( 110, 35 );
  QPalette pal = palette();
  pal.setColor( QPalette::Background, Qt::black ); // space is black, isn't it?
  setPalette( pal );
  resize( 500, 500 );

.
alt text

+3

Source: https://habr.com/ru/post/1779757/


All Articles