简体   繁体   English

调用 QGraphicsScene::advance() 后,我的项目没有重绘

[英]After call QGraphicsScene::advance() my item not redrawn

I was trying to do a simple animation on QGrapichScene.我试图在 QGrapichScene 上做一个简单的动画。 I implemented void QGraphicsItem::advance(int) in class, that inherites QGraphicsItem, but after calling advance() my item not redrawn.我在继承 QGraphicsItem 的类中实现了void QGraphicsItem::advance(int) ,但是在调用advance()我的项目没有重绘。 In colliding mice example it works.碰撞鼠标示例中它有效。 What have I done wrong?我做错了什么?

Here is my code:这是我的代码:

widget.h:小部件.h:

class Widget : public QWidget
{
    Q_OBJECT

private:
    QGraphicsScene *scene;
    QGraphicsView *view;
    QHBoxLayout *layout;
    QTimer t;

public:
    Widget(QWidget *parent = 0);
    ~Widget();
};

widget.cpp:小部件.cpp:

Widget::Widget(QWidget *parent) : QWidget(parent)
{
    layout = new QHBoxLayout(this);

    view = new QGraphicsView(this);
    scene = new QGraphicsScene(0, 0, 400, 400, view);

    scene->addItem(new MyItem());

    view->setScene(scene);
    layout->addWidget(view);

    setLayout(layout);

    connect(&t, SIGNAL(timeout()), scene, SLOT(advance()));

    t.start(100);
}

Widget::~Widget()
{

}

my_item.h: my_item.h:

class MyItem : public QGraphicsItem
{
private:
    QRect bRect;

    enum directon { left, right };

    directon currentDir;

protected:
    virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

public:
    MyItem(int w = 20);

    virtual void advance(int phase);
    virtual QRectF boundingRect() const
    { return QRectF(bRect); }
};

my_item.cpp: my_item.cpp:

MyItem::MyItem(int w)
{
    currentDir = right;
    bRect = QRect(0, 0, w, w);
}

void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    qDebug() << "In void MyItem::paint(QPainter*, "
                "const QStyleOptionGraphicsItem*, "
                "QWidget*)";

    painter->fillRect(bRect, Qt::red);
}

void MyItem::advance(int phase)
{
    qDebug() << "In void MyItem::advance(int);"
             << "Phase =" << phase;
    if(!phase) 
        return;
    // Than move item to new positon...
}

It's on you to inform the graphics scene that your item's contents have changed.您需要通知图形场景您的项目内容已更改。 You have to call update() at the end of advance() .您必须在update()结束时调用update() advance() If you're simply moving the item, without changing its contents, then you don't need to call update() of course - the scene will detect such changes automatically.如果您只是移动项目而不更改其内容,那么您当然不需要调用update() - 场景会自动检测此类更改。

I found something strange:我发现了一些奇怪的东西:

connect(&timer, SIGNAL(timeout()), scene, SLOT(advance()));

The slot need to combined after the Widget is shown, or the slot will never been called!显示Widget后需要合并slot,否则slot永远不会被调用!

As the Qt example shown, you can combine it in the main function.如 Qt 示例所示,您可以将其组合在主函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM