[英]How can I update a QLabel over a period of time?
我正在尝试创建一个程序以在桌面上显示通知。 我首先使用了QLabel,它在每次更改音量时都会弹出。
在这里,我有一个函数,它将QLabel和字符串作为参数,并使用字符串的文本更新标签:
void displayNotif (QLabel* label, int labelText) {
labelStr = QString::number(labelText) + "% volume";
label -> setText(labelStr);
label -> raise();
label -> show();
//Animation
QPropertyAnimation *slideIn = new QPropertyAnimation(label, "pos");
slideIn->setDuration(750);
slideIn->setStartValue(QPoint(1800, 30));
slideIn->setEndValue(QPoint(1250, 30));
slideIn->setEasingCurve(QEasingCurve::InBack);
slideIn->start();
// Wait 3 seconds
QEventLoop loop;
QTimer::singleShot(3000, &loop, SLOT(quit()));
loop.exec();
// Close block
label -> hide();
}
在主循环中调用此函数,该循环每1秒等待一次,并检查音量是否已更改。 我的问题是,每当我增加音量超过一秒时,对话框最终就会显示两次(或更多),这是有道理的,因为它会再次检查并且音量与第二秒之前不同。
我想做的是让标签持续显示三秒钟,但是据我所知,您可以
while( loop.exec() ) { //UpdateLabel }
我该怎么做? 如果音量仍在增加/减小,则可以使它显示更长的时间。
提前致谢!
编辑:
调用displayNotif的主要功能如下所示:
#include <QApplication>
#include <QLabel>
#include <QProcess>
#include <QTimer>
#include "getBattery.h"
#include "getVolume.h"
#include "displayNotif.h"
#include "AnimatedLabel.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
// Create Label
QLabel *hello = new QLabel();
int vol;
vol = getVolume();
QEventLoop loop;
while (true) {
//Check if volume is updated
if (getVolume() != vol) {
vol = getVolume();
displayNotif (hello, vol);
}
// Wait .2 second
QTimer::singleShot(200, &loop, SLOT(quit()));
loop.exec();
}
return app.exec();
}
不需要使用True来完成此重复性任务,只需使用QTimer
,使用QEventLoop
时就不会留下任何方式来更新GUI的任何组件。
#include <QApplication>
#include <QLabel>
#include <QTimer>
#include <QDebug>
#include <QPropertyAnimation>
class NotifyLabel: public QLabel{
Q_OBJECT
QTimer timer{this};
QPropertyAnimation slideIn{this, "pos"};
public:
NotifyLabel(){
timer.setSingleShot(true);
timer.setInterval(3000);
connect(&timer, &QTimer::timeout, this, &NotifyLabel::hide);
slideIn.setDuration(750);
slideIn.setStartValue(QPoint(1800, 30));
slideIn.setEndValue(QPoint(1250, 30));
slideIn.setEasingCurve(QEasingCurve::InBack);
}
void displayNotif(int value){
if(timer.isActive()){
timer.stop();
}
else
slideIn.start();
setText(QString("%1% volume").arg(value));
show();
timer.start();
}
};
static int getVolume(){
// emulate volume
return 1+ rand() % 3;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
NotifyLabel w;
QTimer timer;
int current_vol;
QObject::connect(&timer, &QTimer::timeout, [&w, ¤t_vol](){
int update_vol = getVolume();
qDebug()<<update_vol;
if(current_vol != update_vol){
w.displayNotif(update_vol);
}
current_vol = update_vol;
});
timer.start(2000);
return a.exec();
}
#include "main.moc"
在下面的链接中,您将找到完整的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.