Sending signal in Special Time like hh:mm with Qt - c++

I am trying to send a signal in special time like every day in 22:23 o'clock with Qt Library.
I want to use something like this function:
QTimer::singleShot("22:23", this, SLOT(updateCaption()));
I don't want to use if statements in my code and check time. i mean:
if( time == "22:23" )
emit mysignal();
how is it possible?

Here's how I'd do this.
First, get the datetime of the next time you want to emit the signal:
auto then = QDateTime::currentDateTime();
auto setTime = QTime::fromString("22:23", "hh:mm");
if(then.time() > setTime){
then = then.addDays(1);
}
then.setTime(setTime);
calculate the time difference from now
auto diff = QDateTime::currentDateTime().msecsTo(then);
and start a singleshot timer at that time, to start the regular daily timer:
QTimer::singleShot(diff, [this]{
auto t = new QTimer(QCoreApplication::instance());
connect(t, &QTimer::timeout, [this]{
emit mysignal();
});
t->start(24 * 3600 * 1000);
});
Note that this will be an hour off when the daylight saving time changes.

I've done a brief search and found this solution, looks pretty smooth:
QDateTime now = QDateTime::currentDateTime();
QDateTime timeoftheaction = ...;
QTimer *timer=new QTimer;
connect(timer, SIGNAL(timeout()),object,SLOT(action);
timer->start(now.secsTo(timeoftheaction)*1000);
Of course you can write a function and call it with the single line

Related

Creating a simple Clock in QT

I want to create a simple clock in my Qt program: QLabel which is updated once a second.
QLabel name: label_clock
My clock "script":
while (true)
{
QString time1 = QTime::currentTime().toString();
ui->label_clock->setText(time1);
}
But when I pase it into my program, you already know that it will stop executing it at this script - while will always give true, so rest of code under script will never execute -> program crashes.
What should I do to make this script work? I wanna create a simple clock which is being updated once a second.
You can use QTimer for this. Try something like this:
QTimer *t = new QTimer(this);
t->setInterval(1000);
connect(t, &QTimer::timeout, [&]() {
QString time1 = QTime::currentTime().toString();
ui->label_clock->setText(time1);
} );
t->start();
Of course you should enable c++11 support (add to your pro file CONFIG += c++11).

passing a current time variable

I am trying to get a text edit box to display the current time every 5 seconds using QTimer. I am having the current time figured in a separate method and then having the QTimer call that method and display the current time. I can not for the life of me figure out how to pass the variable from the setCurrentTime method to the QTimer. Im sure it a really easy fix but I cant figure it out. Here is my code.
void noheatmode::setCurrentTime()
{
QTime time = QTime::currentTime();
QString sTime = time.toString("hh:mm:mm");
// ui->tempTimeNoHeatMode->append(sTime);
}
void noheatmode::on_timeButton_clicked()
{
QTimer *timer =new QTimer(this);
connect(timer,SIGNAL(timeout()), this, SLOT(setCurrentTime()));
timer->start(5000);
ui->tempTimeNoHeatMode->append(sTime);
}
If I got your problem right, you just have minutes variable instead of a seconds. Just change "hh:mm:mm" to "hh:mm:ss"
void noheatmode::setCurrentTime()
{
QTime time = QTime::currentTime();
QString sTime = time.toString("hh:mm:ss");
ui->tempTimeNoHeatMode->append(sTime);
}
With your code:
void noheatmode::on_timeButton_clicked()
{
QTimer *timer =new QTimer(this);
connect(timer,SIGNAL(timeout()), this, SLOT(setCurrentTime()));
timer->start(5000);
ui->tempTimeNoHeatMode->append(sTime);
}
This means that the function within SLOT will be called every 5000 milliseconds which = 5 seconds. What could be done then is that you set your function setCurrentTime() to update your text box every time it is called.
Example:
void Class::setCurrentTime()
{
QTime times = (QTime::currentTime());
QString currentTime=times.toString("hh:mm:ss");
ui->label->setText(currentTime);
//Assuming you are using a label to output text, else substitute for what you are using instead
//Every time this function is called, it will receive the current time
//and update label to display the time received
}

100% CPU utilization in either gettimeofday, QTime or QLabel->setText

I've been working on a simple dialog widget that should display GMT time at a rate of 10 Hz. Since the system I'm working on runs for days and days, it should be stable.
On some overnight runs, I've noticed that my "BAR" program is running at 100 % after several hours of execution. I'm flummoxed as to why this occurs, but I've been able to narrow it down to three functions:
I'm using a simple function called ace_time to obtain time of day:
inline double ace_time(void)
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return (double) tv.tv_sec + 1e-6 * (double) tv.tv_usec;
}
And then I obtain the milliseconds, seconds, minutes, etc, from the return of this function. I then use QTime to format it:
QTime time(hours, minutes, seconds, milliseconds);
QString timeStr = time.toString("hh:mm:ss.zzz");
And then set the text in my label:
clock->setText(timeStr);
I'm confused why I would get 100 % cpu usage, unless gettimeofday, QTime or setText are doing things that I'm not expecting.
Have the experts here noticed any of these functions behaving strangely?
I'm using Qt 4.8, if that helps.
Looking forward to getting some ideas to solve this. Thanks!
Adding more code:
I want to have two bars. A top and a bottom bar. So I've written a BarBase class and a TopBar class. I also needed to write a custom QLayout to help me with the layout. I highly doubt the layout manager is causing this because it is only called when the bar is resizing and the geometry needs to be recalculated.
class BarBase : public QWidget
{
public:
BarBase()
{
setFixedHeight(barHeight);
setContentsMargins(5, 0, 5, 0);
QPalette palette;
QColor color(50, 252, 50);
palette.setColor(QPalette::Background, color);
setAutoFillBackground(true);
setPalette(palette);
}
virtual ~BarBase();
protected:
QLabel *createWestLabel(const QString &);
QLabel *createCenterLabel(const QString &);
QLabel *createEastLabel(const QString &);
private:
QLabel *createLabel(const QString &, Qt::Alignment)
{
QLabel *label = new QLabel(str);
label->setAlignment(Qt::AlignVCenter | alignment);
//label->setFrameStyle(QFrame::Box | QFrame::Raised);
QFont font("Times");
font.setPixelSize(barHeight - 4);
font.setBold(true);
label->setFont(font);
return label;
}
};
And here is my class for the TopBar only
class TopBar : public BarBase
{
Q_OBJECT
public:
TopBar()
{
Layout *layout = new Layout;
classification = createCenterLabel("Classification");
layout->addWidget(classification, Layout::Center);
hostname = createWestLabel("Hostname");
layout->addWidget(hostname, Layout::West);
layout->addWidget(createWestLabel(":"), Layout::West);
software = createWestLabel("Software");
layout->addWidget(software, Layout::West);
runMode = createEastLabel("SIM");
layout->addWidget(runMode, Layout::East);
layout->addWidget(createEastLabel(":"), Layout::East);
clock = createClockLabel("-dd::hh::mm::ss.z");
layout->addWidget(clock, Layout::East);
deadman = new QTimer;
connect(deadman, SIGNAL(timeout()), this, SLOT(updateLocalGMT()));
deadman->start(100); // 10 ms;
setLayout(layout);
setWindowTitle(tr("Top Bar"));
}
virtual ~TopBar();
public slots:
void updateLocalGMT()
{
double milliseconds = fmod(ace_time(), 86400.0) * 1000;
bool sign = (milliseconds >= 0.0);
if (!sign)
{
milliseconds = -milliseconds;
}
const int millisecondsToDays = 86400.0 * 1000.0;
const int millisecondsToHours = 3600.0 * 1000.0;
const int millisecondsToMinutes = 60 * 1000.0;
const int millisecondsToSeconds = 1000.0;
double days = floor(milliseconds / millisecondsToDays);
milliseconds -= days * millisecondsToDays;
double hours = floor(milliseconds / millisecondsToHours);
milliseconds -= hours * millisecondsToHours;
double minutes = floor(milliseconds / millisecondsToMinutes);
milliseconds -= minutes * millisecondsToMinutes;
double seconds = floor(milliseconds / millisecondsToSeconds);
milliseconds -= seconds * millisecondsToSeconds;
QTime time(hours, minutes, seconds, milliseconds);
/*
if (!time.isValid())
{
INFO("Invalid input to QTime [day, hour, min, sec, ms]: [%f %f %f %f %f]",
days, hours, minutes, seconds, milliseconds);
}
*/
QString timeStr = time.toString("hh:mm:ss.zzz");
timeStr = timeStr.left(timeStr.length() - 2); // to remove the last two z
timeStr.prepend((sign) ? "+" : "-");
timeStr.prepend("<code style='color:white'>");
timeStr.append("</code>");
// timeStr = timeStr.left(timeStr.length() - 2);
// qDebug() << currentTime;
clock->setText(timeStr);
}
private:
QLabel *classification;
QLabel *hostname;
QLabel *software;
QLabel *runMode;
QLabel *clock;
QLabel *createClockLabel(const QString &text)
{
QLabel *label = new QLabel(text);
label->setAlignment(Qt::AlignVCenter);
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
font.setFixedPitch(true); // enforces monospace
font.setPointSize(18);
font.setBold(true);
label->setFont(font);
int pixelWidth = label->fontMetrics().width(label->text());
label->setFixedWidth(pixelWidth);
return label;
}
QTimer *deadman;
};
The QTimer can fall behind and queue up many notifications if your thread is busy - this will cause your processing to happen far more than you expect.
To workaround this you should do something like:
void timer_slot()
{
if diff(now - last_time) < timer_interval
return; // Timer has come in too early so don't do anything
last_time = now;
}
If you want to reproduce this just block your thread with a sleep() and you'll notice that the timer slot will be called for as many times as it should have been called while the thread was blocked.
The QTimer docs state that:
"Accuracy and Timer Resolution
Timers will never time out earlier than the specified timeout value and they are not guaranteed to time out at the exact value specified. In many situations, they may time out late by a period of time that depends on the accuracy of the system timers.
The accuracy of timers depends on the underlying operating system and hardware. Most platforms support a resolution of 1 millisecond, though the accuracy of the timer will not equal this resolution in many real-world situations.
If Qt is unable to deliver the requested number of timer clicks, it will silently discard some."
But I've found this not to be true on Windows 7 x64 if the thread is blocked/busy.
deadman->start(10); // 10 ms;
(Note: answer written before question was fixed to have 100 ms interval)
You have 10ms interval here, which is 100Hz, not 10Hz. In your question you say "the system I'm working on runs for days and days", so it sounds like you have an embedded system of some sort? Maybe it has trouble keeping up with 100Hz timer.
Note that updating the label 100 times a second will cause QWidget::update() to be called that often, and the widget will be painted from event loop very often, even if you do not call repaint() (which you should not do anyway).

QTime QTimer timeout() driven Stopwatch has high CPU usage

In my game I need a stopwatch to measure and show the elapsed time.
For this purpose I made a simple widget:
ZuulStopwatchWidget::ZuulStopwatchWidget(QWidget *parent) :
QWidget(parent)
{
num = new QLCDNumber(this); // create the display
num->setDigitCount(9);
time = new QTime();
time->setHMS(0,0,0,0); // set the time
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(showTime()));
i=0;
QString text = time->toString("hh:mm:ss");
num->display(text);
//num->setStyleSheet("* { background-color:rgb(199,147,88);color:rgb(255,255,255); padding: 7px}}");
num->setSegmentStyle(QLCDNumber::Flat); //filled flat outline
//setStyleSheet("* { background-color:rgb(236,219,187)}}");
layout = new QVBoxLayout(this);
layout->addWidget(num);
setMinimumHeight(70);
}
ZuulStopwatchWidget::~ZuulStopwatchWidget()
{
// No need to delete any object that has a parent which is properly deleted.
}
void ZuulStopwatchWidget::resetTime()
{
time->setHMS(0,0,0);
QString text = time->toString("hh:mm:ss");
num->display(text);
i=0;
stopTime();
}
void ZuulStopwatchWidget::startTime()
{
//flag=0;
timer->start(1);
}
void ZuulStopwatchWidget::stopTime()
{
timer->stop();
}
void ZuulStopwatchWidget::showTime()
{
QTime newtime;
//if(flag==1)
//i=i-1;
i=i+1;
newtime=time->addMSecs(i);
QString text = newtime.toString("mm:ss:zzz");
num->display(text);
}
But when I run my game the CPU usage is at about 13% on a 2,5Ghz i5. I know this is not problematic but it sure is ridiculous for a stupid clock.
Am I doing it completely wrong or is this common practice ?!
Many thanks in advance.
Start(1) sets the timer to trigger every millisecond
You then want to format a string and print it on the screen 16times faster than the screen is probably updating anyway

Qt - QTimeEdit as a timer viewer

I have a QTimeEdit which I want to set to some value and the each second I want to decrease by 1 the value that shows the QTimeEdit. So when it will be 0, the I want to have a QMeesageBox that says "Your time is off.". Can I some how do this with QTimeEdit interface, or I should use QTimer?
You can use QTimeEdit for displaying the time but you will have to use QTimer to decrease the time every second.
You can do something like this:
timeEdit->setTime(...); //set initial time
QTimer timer;
timer.start(1000); //timer will emit timeout() every second
connect(&timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));
void slotTimeout()
{
QTime time = timeEdit->time().addSecs(-1);
timeEdit->setTime(time);
if (time == QTime(0, 0))
//time is zero, show message box
}