I am trying to make a simple game under Qt 4.6. The idea is to have two widgets, one is the main window widget and represents the space and the second one is a starship widget inside the space (parent). Simplified code looks like this:
/*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 rectangle MyRect::body
is not drawn.
I checked the Qt online documentation and did some google research with no luck.
Any explanation about this is welcome. I want to draw one widget on anothe开发者_JAVA百科r (parent).
• QPainter painter(itsParent);
- wrong. You should draw only on this widget's surface, not on parents. So correct will be QPainter painter(this);
• You should not save widgets body in MyRect class. Class space must keep its size and position. So in MyRect::paintEvent()
change painter.drawRect(*body);
to painter.drawRect( rect() );
• So class MyRect
should have no members at all.
• Last thing remained: in space::space()
add
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 );
and voila.
精彩评论