1

我试图每秒在 QGraphicsView 中移动一个图像,我尝试了四种方法,但没有一个对我有用。

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

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

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

问题是,每经过第二次,框架上的图像就会移动到下一个位置,直到达到极限,然后停止移动。我不知道延迟是不是最好的方法,但我需要每秒移动一次图像,方式无关紧要。谢谢阅读。

4

3 回答 3

0

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

于 2014-04-05T10:56:15.757 回答
0

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

至于使用QTimer,我会阅读有关它的官方文档。它给了你很好的,可能是最权威的答案。

为方便起见,这是内联的要点:

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

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

从那时起,update() 插槽每秒被调用一次。

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

于 2014-04-05T04:26:01.953 回答
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
}
于 2014-04-05T04:15:06.427 回答