gpt4 book ai didi

c++ - QGraphicsView/QGraphicsScene 定时器事件不工作

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:50 27 4
gpt4 key购买 nike

我试图在 qgraphicsview 中实现一个基本的 qtimer,但似乎无法让它工作。

这是我的 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();
}

这是 View 标题...注意 qtimer 和 advance 函数

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



}

最佳答案

您需要在头文件中将 advance() 函数声明为一个插槽。否则 Qt 不知道这个特定的函数是一个槽:

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

然后,您将超时信号连接到场景中的 advance() 插槽 - 但您在 View 中声明了它。当您当前在 View 中时,您可以使用 this 指针将信号连接到您的 View 。像这样更改您的连接:

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

[编辑] 作为侧节点:您正在创建类型为Game 的QGraphicsView 子类,但您显示了View 的源代码。不过,如果 Game 继承自 View,这可能无关紧要。

关于c++ - QGraphicsView/QGraphicsScene 定时器事件不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13007136/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com