PDA

View Full Version : Implementation of timer makes the program to continuously slow down



Yorma
20th January 2006, 12:42
The main idea is to have time shown on Qtable (is there a better class for it?) on main widget. At first the time is updated correctly every second, but after ~10 seconds the time is updated only every 2, 3, etc seconds. Now I think for some reason something makes the program slow down, and for that the clock is updated more infrequent. There may be some loop that i cant notice that continues to eat up the resources more and more after each update:


class test : public QObject
{
Q_OBJECT
public:
test(QWidget *qwi,QLabel *qlb);

public slots:
void upd();

private:
QWidget *qw;
QLabel *ql;
};

test::test(QWidget *qwi, QLabel *qlb)
{
qw = qwi;
ql = qlb;
}

void test::upd()
{
QTimer *timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(upd()));
timer->start(1000);
QTime time = QTime::currentTime();
QString str = "<font color='green'>";
str.append(time.toString("hh:mm:ss"));
str.append("</font>");
ql->setText(str);
qw->update();
}


int main (int argc, char *argv[])
{
QApplication app(argc, argv);

QWidget window;

window.resize(1024, 768);
QLabel *timeLabel = new QLabel(&window);
timeLabel->setFrameStyle(QFrame::NoFrame | QFrame::Plain);
timeLabel->setFont(QFont("Times", 20, QFont::Bold));
timeLabel->setAlignment(Qt::AlignBottom | Qt::AlignRight);
QString str = "<font color='green'>";
QTime time = QTime::currentTime();
str.append(time.toString("hh:mm:ss"));
str.append("</font>");
timeLabel->setText(str);

QPalette palette(QApplication::palette());
window.setParent(0,Qt::FramelessWindowHint);
palette.setColor(QPalette::Background, QColor("Black"));
QPushButton quit("Quit", &window);
quit.setFont(QFont("Times", 18, QFont::Bold));
palette.setColor(QPalette::Button, QColor("Blue"));
window.setPalette(palette);
quit.setPalette(palette);
quit.setGeometry(974, 0, 50, 20);
QObject::connect(&quit, SIGNAL(clicked()), &app, SLOT(quit()));


window.show();

test *t = new test(&window,timeLabel);
t->upd();
return app.exec();
}

#include "main.moc"

jacek
20th January 2006, 13:01
Now I think for some reason something makes the program slow down, and for that the clock is updated more infrequent. There may be some loop that i cant notice that continues to eat up the resources more and more after each update:


void test::upd()
{
QTimer *timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(upd()));
timer->start(1000);
// ...
}
Every time you invoke test::upd() you create a new timer, so after first second your will have 2 timers, after second one --- 4, then 8, 16, 32, ..., and after a minute you will have about 10^19 timers.

Create that timer only once.