每秒钟在QGraphicsView中移动图像

时间:2014-04-05 04:01:24

标签: c++ qt qthread qtcore qtimer

我试图每秒在QGraphicsView中移动一个图像,我尝试了四种方法,但它们都没有为我工作。

1)我使用QTest,使用QTest :: qSleep()函数,但这根本不起作用,导致应用程序中出现两个错误,我认为必须与项目的.pro文件一起使用。

2)我在第二次尝试中使用QThread,至少QThread :: sleep(),应用程序运行,但图像已经在我之前设置的最后位置。我的意思是,睡眠不起作用(工作一段时间,但是以不同的方式,一旦完成循环并且睡眠在循环内工作,应用程序有时会出现在屏幕上。有时冻结并且不显示App。)

3)我使用了一个用户在其他问题上发帖的功能,他说是睡眠功能的替代品。

QTime dieTime= QTime::currentTime().addSecs(1);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

4)我也使用了QWaitCondition,这是另一种选择。

QMutex dummy;
dummy.lock();
QWaitCondition waitCondition;
waitCondition.wait(&dummy, waitTime);

我读过有关QTimer的内容,但我还不知道如何使用它,我是QT的初学者,我只知道基础知识。 所有我试过的都是在while循环中做的。

我需要实施的代码:

void Window::start(PilaD *caminoGato,PilaD *caminoRaton){
 /*
 YOU DONT NEED TO UNDERSTAND THIS CODE
 Nodo *recorGato,*recorRaton;
 recorGato = new Nodo();
 recorRaton = new Nodo();
 recorGato = caminoGato->tope;
 recorRaton = caminoRaton->tope;
 By The Way, for you to understand, recorGato is a class, this class have two variable row and col
 */


 QPixmap *icon = new QPixmap(list.at(2));
 QGraphicsPixmapItem *gato = new QGraphicsPixmapItem(*icon);
 scene->addItem(gato);

 while(recorGato!=NULL){
    //ALL I TRIED, I PLACE IT HERE, INSIDE THE LOOP
    gato->setPos(recorGato->col*icon->width()+200,recorGato->row*icon->height()+100);
    recorGato = recorGato->pre;
 }
} 

事情是,每次第二次传球时,帧上的图像移动到下一个位置,直到达到极限,然后停止移动。我不知道延迟是否是最佳方式,但我需要每秒移动一次图像,这种方式并不重要。感谢阅读。

3 个答案:

答案 0 :(得分:0)

尝试使用带有插槽的QTimer。我只写一个sudo代码。

void MyClass::myFunc()
{
    mTimer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(slotMoveImage()));
    mTimer->start(1000); // set timeout for 1 second
 }


/***Slot will look something like this**/

void MyClass::slotMoveImage()
{
 // Move image and restart the timer. Do not restart if we don't want to move further
  img->setPos(img.rect().x() + 200, img.rect.y()+100);
  if(/* not some condition */)
     mTimer->start(1000); // again start the timer
}

答案 1 :(得分:0)

有点难以理解为什么之前试验的某些部分没有奏效,因为你没有分享太多细节。

关于使用QTimer,我会阅读有关它的official documentation。它给你很好的,也许是最权威的答案。

以下是为方便起见的内线:

  

一秒(1000毫秒)定时器的示例(来自模拟时钟示例):

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(1000);
  

从那时起,每秒都会调用update()槽。

这将为您提供异步(即非阻塞)解决方案,而不是之前的“睡眠”操作。这样,与睡眠不同,您的代码仍然具有响应性。

答案 2 :(得分:0)

请使用QTimeLine - 这是要走的路。

相关问题