Qt -在特定时间创建通知(PC)

Qt - Creating a notification at a certain time (PC)

本文关键字:通知 PC 创建 定时间 Qt      更新时间:2023-10-16

在学校,我必须用Qt为个人电脑创建一个日历程序,此日历还必须在某些预定约会开始前的特定时间发出通知。

但是我很难找出我究竟如何可以创建这个通知而不使用while循环(这将停止我的程序),我真的很感激如果有人能帮助我一点与我的项目的某些部分。

谢谢你,丹尼斯

可以创建一个时间间隔为1秒的QTimer实例。然后连接QTimer::timeout()信号,在插槽中可以查看是否有约会临近,如下所示:

void YourClass::slotNameForTimeoutSignal()
{
    static const int fifteenMinutes = 15 * 60;
    foreach (const Appointment& app : allAppoitments)
    {
        if ((app.getStartUnixTime() - QDateTime::currentDateTime().toTime_t()) <= fifteenMinutes)
        {
            notifyAboutTheAppointment(app); // implement this method to display notification
        }
    }
}

这段代码假设你有某种Appointment类/结构,在约会开始时保存unix时间。定时器设置很简单。在应用程序初始化的某个地方创建一个计时器(它应该是类中的成员字段),设置它并运行:

YourClass::YourClass()
{
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(slotNameForTimeoutSignal()));
    timer->setInterval(1000);
    timer->setSingheShot(false);
    timer->start();
}

如果你还不知道的话,unixtime是一种时间格式,它是一个整数——从1970年开始经过的秒数。这里有更多的细节:http://en.wikipedia.org/wiki/Unix_time

如果你不熟悉Qt中的信号/槽,你应该先阅读Qt文档中的那些。

您可以子类化QCalendarWidget来创建您的GUI,即用户可以在他想要约会时选择日期。使用QTimer触发信号在您的精确约会时间。

现在您可以使用QDateTime获得当前日期和时间。

1. Check if the appointment is on the same date as current.
2. If yes jump to step no 4.
3. Set a timer using QTimer to emit a SIGNAL after 24 hours and connect this SIGNAL to your custom SLOT which will check if the current date is same as appointment date. Continue this step until your current date is same as appointment date.
4. Calculate the time difference between  your appointment and current time and set this difference to a QTimer which will emit a SIGNAL at the required time.
5. This emitted SIGNAL would be connected a SLOT in which you are doing whatever is needed when the appointment is reached

我希望这能帮助你步入正轨。写代码就像做作业我可不想做