2014-11-04 79 views
1

当一个按钮按下时,让滑块以给定的速度在一个循环中移动,最直接的方法是什么?我猜测它涉及到一个线程周期性发送适当的信号到滑块。有没有一个规范的方法来做这个例子?Qt:如何自动化背景中的循环滑块运动?

回答

2

我建议使用QPropertyAnimation来完成这项工作。只需设置起始值,最终值和您希望值改变的曲线

QPropertyAnimation *animation = new QPropertyAnimation(slider,"sliderPosition"); 
//set the duration (how long the animation should run - will change value faster when shorter) 
animation->setDuration(1000); 
//set the start value - in this case check if value in range of the slider 
animation->setStartValue(slider->minimum()); 
//same as start value 
animation->setEndValue(slider->maximum()); 
//easingCurve defines if it goes straight or bouncing n stuff 
animation->setEasingCurve(QEasingCurve::OutCubic); 

// as coyote mentioned, you can loop the animation as well (credit him as well ;)) 
// -1 defines to run forever 
animation->setLoopCount(loopCount) 

animation->start(); 
+1

您还可以更改循环计数使其无限期运行 – coyotte508 2014-11-04 15:56:28

+0

谢谢@ coyotte508,已经忘记了该功能 – Zaiborg 2014-11-04 16:02:39

2

这只是更新滑块在计时器上的位置而已。因此,创建一个计时器并在每次更新时,请致电QSlider::setValue

当值最大时,将其设置回最小值并继续。

QSlider* pSlider = new QSlider; 

QButton * pButton = new QButton("Go"); 

QTimer* pTimer = nullptr; // C++ 11 nullptr 

// On button click, start a timer 
connect(pButton, &QButton::clicked(), [=](){ 

    // exit if already running 
    if(pTimer) 
     return;  

    pTimer = new QTimer; 
    connect(pTimer, &QTimer::timeout, [=](){ 

     if(pSlider->value()+1 > pSlider->maximum()) 
      pSlider->setValue(pSlider->minimum()); 
     else 
      pSlider->setValue(++pSlider->value());  
    }); 
    pTimer->start(1000); // update every second 
}); 
1

您可以使用QTimer。小例子:

QSlider *sl = new QSlider; 
QTimer *ttt = new QTimer; 
sl->setValue(0); 

connect(ttt,&QTimer::timeout,[=]() { 
    sl->setValue(sl->value() + 5); 
}); 
sl->show(); 
ttt->start(500); 

我这里使用的C++11CONFIG += c++11.pro文件)和new syntax of signals and slots,当然,如果你愿意,你可以使用旧的语法。

1

我的知识没有规范的方法。

定时器在其他答案中给出,但您也可以使用animation framework,并通过调整动画的持续时间来调整速度。

您可以将loopcount设置为您希望动画运行的次数,例如1000000以使其运行很长时间。