PDA

View Full Version : qtimer and signals



dlthompson81
26th April 2012, 14:53
I worked through a youtube tutorial on signals and slots, and I thought I had a pretty good understanding of it. I tried playing with the code a little bit to test some things, and I thought this should work, but I'm not sure exactly where it goes wrong.

The original program created 2 person objects and had person A tell person B something, and person B then repeated it. What I tried to do was connect a timer to person A to make that person tell person B the same thing every second, but when I run it, the time doesn't make them do anything. I'm not sure where I am going wrong.

I created a test slot just to be sure the timer was ticking, and it is, so I know my problem lies somewhere in the timer connection to the person A slot. Any help or tips would be much appreciated, Thanks!

Here is the code:



#ifndef PERSON_H
#define PERSON_H

#include <QObject>
#include <QString>
#include <QDebug>

class Person : public QObject
{
Q_OBJECT
public:
explicit Person(QObject *parent = 0);

QString Name;



signals:
void Speak(QString words);

public slots:
void Listen(QString words);
void Gossip();

};

#endif // PERSON_H





#ifndef WATERCOOLER_H
#define WATERCOOLER_H

#include <QObject>

class WaterCooler : public QObject
{
Q_OBJECT
public:
explicit WaterCooler(QObject *parent = 0);

signals:

public slots:
void testTimer();

};

#endif // WATERCOOLER_H





#include "person.h"
#include <QTimer>

Person::Person(QObject *parent) :
QObject(parent)
{

}

void Person::Listen(QString Words)
{
qDebug() << Name << " says someone told me... " << Words;
}

void Person::Gossip()
{
QString Words = " says I heard so and so did something.";
qDebug() << Name << Words ;
emit Speak(Words);
}





#include "watercooler.h"
#include "person.h"
#include <QTimer>

WaterCooler::WaterCooler(QObject *parent) :
QObject(parent)
{
Person Cathy;
Person Bob;

Cathy.Name = "Cathy";
Bob.Name = "Bob";

connect(&Cathy, SIGNAL(Speak(QString)), &Bob, SLOT(Listen(QString)));

QTimer *timer = new QTimer(this);
connect ( timer, SIGNAL(timeout()), &Cathy,SLOT(Gossip()));
connect ( timer, SIGNAL(timeout()), this, SLOT(testTimer()));
timer->start(1000);

Cathy.Gossip();
}

void WaterCooler::testTimer()
{
qDebug() << "Timer working." << endl;
}

viulskiez
26th April 2012, 15:00
Look at WaterCooler constructors.
you have this code:

Person Cathy;
Person Bob;
It's mean when WaterCooler instance constructed, Cathy and Bob destroyed because both are not pointer.
It's safe to use pointer and set the parent to WaterCooler instance so both of them destroyed when WaterCooler instance destroyed.


Person* Cathy = new Person(this);
Person* Bob = new Person(this);

dlthompson81
26th April 2012, 15:56
Ah, that was the problem. I guess I forgot I was writing the code in the constructor. Thanks for the help.