2012-10-22 84 views
1

我试图在qgraphicsview中实现一个基本的qtimer,但似乎无法让它工作。QGraphicsView/QGraphicsScene Timer事件不起作用

这里是我的main.cpp代码:

int main(int argc, char * argv[]) { 


    QApplication app(argc, argv);//should stay on the stack 

    QGraphicsScene * scene = new QGraphicsScene();//this is the scene -- the canvas that holds everything! 

    // a view just adds stuff to the scene in that view port 

    QGraphicsView * view = new Game(scene);//create a new view 

    return app.exec(); 
} 

这里是视野头......注意qtimer和推进功能

class View: public QGraphicsView {//inherits qwidget -- so we can make it full screen there 

    Q_OBJECT 

    public: 
     View(QGraphicsScene * _scene);//this is responsible for setting up the screen and instantiating several elements 
     ~View(); 

    protected://variables 
     QGraphicsScene * scene; 
     QTimer * timer; 


    protected://functions 

     int const int_height();//converts qreal to an int 
     int const int_width(); 

     qreal const height();// 
     qreal const width();//this is the actual qreal floating point number 

     virtual void paintEvent(QPaintEvent * event) {}; 
     void timerEvent(QTimerEvent * event) {cout << "HELLO << ads" << endl;}; 
     virtual void keyPressEvent(QKeyEvent * event) {}; 
     virtual void update() = 0; 


     void advance() { cout << "HELLO WORLD" << endl;}   
    private: 
     qreal _height; 
     qreal _width; 

}; 

最后,我认为实现构造函数:

View::View(QGraphicsScene * _scene) : QGraphicsView(_scene) { 


    scene = _scene;//set the scene which is the parent over this 


    this->showMaximized(); 

    QRectF geometry = this->contentsRect(); 

    _height = geometry.height(); 
    _width = geometry.width(); 

    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); 

    scene->setSceneRect(0, 0, this->int_width(), this->int_height()); 
    // this->centerOn(qreal(0), qreal(0)); 

    this->setGeometry(0, 0, _width, _height); 
    this->setFixedSize(_width, _height); 


    timer = new QTimer(this); 
    connect(timer, SIGNAL(timeout()), scene, SLOT(advance())); 
    timer->start(1000); 
    timer->setInterval(100); 



} 
+0

你预期会发生什么? 'QGraphicsScene :: advance()'只是告诉其中的所有项目'advance()'。 – cmannett85

回答

1

您需要将您的advance()函数声明为头文件中的插槽。否则,Qt不知道这个特殊的功能插槽:

protected slots: 
    void advance() { cout << "HELLO WORLD" << endl; } 

然后,您连接超时信号,在场景中的提前()槽 - 但你在你的看法宣布它。正如您目前所看到的,您可以使用指针this将信号连接到您的视图。改变你的连接是这样的:

connect(timer, SIGNAL(timeout()), this, SLOT(advance())); 
//        ^^^^ 

[编辑]作为一个边节点:您正在创建Game型的QGraphicsView子类,但你表现出的View的源代码。如果Game继承自View,这可能是无关紧要的。

+0

感谢您的帮助,是的,游戏继承了视图,但我认为它会更容易显示在线观看片:) – JonMorehouse