2016-09-27 75 views
0

我需要制作一个使用Qt的音乐播放器,其中滑块随着歌曲的进展而滑动。无法使horizo​​ntalSlider以固定时间间隔滑动

this->ui->horizontalSlider->setValue(10); 
sleep(1); 
this->ui->horizontalSlider->setValue(20); 

我试图之类的东西上面,但不能使其显示的变更值,因为程序暂停1秒和仅显示所述第二值(20)。

我该如何做到这一点?

+1

什么都不会发生,除非你允许的情况下循环继续。你究竟在努力实现什么? –

+0

滑块应该滑动,就像每秒钟后的进度条(以秒/ 100为单位的歌曲值长度)。所以我在尝试类似的东西,显示价值,睡1秒,显示下一个值,睡眠等等。 –

+1

查看['QTimer'](http://doc.qt.io/qt-5/qtimer.html)并将'QTimer :: timeout'信号连接到更新滑块的函数。 –

回答

2

无论您用于音频播放的库应该异步通知您播放文件的进度。你应该对这种进展做出反应并更新滑块。即使我们忘记阻止事件循环的事实,使用硬编码延迟也会很快地使滑块与实际音频播放不同步。

在任何现代应用程序开发框架中,通常不需要阻塞线程进入休眠状态。如果你写这样的代码,在99.99%的情况下这是错误的方法。

+0

的确,在玩游戏时,对于所有用户交互(以及非输入事件),您将有1秒的滞后时间。这会导致非常糟糕的用户体验。 – Aaron

1

睡觉会阻止程序1秒钟。意味着发生的任何事情(音乐播放,或者在您的应用程序中运行的任何进程)基本上都不起作用。

会发生什么情况是程序会将该值设置为10,睡眠一秒钟(什么都不会发生),设置20,并再次阻止程序1秒钟。所以基本上,你的程序一直都在阻塞,并且每秒都会设置滑块的值。

的解决方案是让进度值,例如:

int total_time, current_time; //Durations in seconds 
int progress; //Will hold the progress percentage 

//Somehow you get the total song time and the current song timer 
//... 
progress = (current_time/total_time)*100 
this->ui->horizontalSlider->setValue(progress); 

或者:

/*When initializing the slider*/ 
int total_time; //Duration in seconds 
//Somehow you get the the total song time... 
//... 
this->ui->horizontalSlider->setRange(0,total_time); 

而在你的日常

/* In the routine where you refresh the slider */ 
int current_time; //Duration in seconds 

//Somehow you get the the current song timer... 
//... 
this->ui->horizontalSlider->setValue(current_time);