如何在一段时间内更新 QLabel?

How can I update a QLabel over a period of time?

本文关键字:更新 QLabel 一段时间      更新时间:2023-10-16

我正在尝试创建一个程序来在我的桌面上显示通知。我开始使用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();
}

此函数在 main 中的循环中调用,该循环每 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, &current_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"

在下面的链接中,您将找到完整的示例。