【问题标题】:problem with painting one widget inside another one (parent)在另一个(父级)中绘制一个小部件的问题
【发布时间】:2010-12-11 17:18:58
【问题描述】:

我正在尝试在 Qt 4.6 下制作一个简单的游戏。这个想法是有两个小部件,一个是主窗口小部件,代表空间,第二个是空间内的星舰小部件(父级)。 简化后的代码如下所示:

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

当我编译时,屏幕是空白的,并且没有绘制矩形MyRect::body。 我检查了 Qt 在线文档并没有运气做了一些谷歌研究。 欢迎对此进行任何解释。我想在另一个(父级)上绘制一个小部件。

【问题讨论】:

  • 我建议也看看QGraphicsView。

标签: c++ qt qt4


【解决方案1】:

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

瞧。

【讨论】:

  • 非常感谢您的回答。我正在用女朋友的笔记本写东西,直到我回家后才能再次编译,但认为这是一个很好的。顺便说一句,我住在克罗地亚(萨格勒布市),在这里向你们所有人致以许多问候,并为即将到来的圣日致以最美好的祝愿。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 2014-09-01
  • 1970-01-01
相关资源
最近更新 更多