[Qt-interest] Basic QThread question - part 2

Phil phillor at telstra.com
Mon May 3 06:53:10 CEST 2010


Thank you for reading this.

I have not progressed very far since my last question on this topic. The code 
that follows came from a Google search. It was incomplete and I have tried 
to add the missing pieces. It results in two error messages:

"undefined reference to CookingClock::secondTicked(int)".
"collect2: Id returned 1 exit status"

The second error message results from including Q_OBJECT in the thread 
class.

Cooker.h

#ifndef COOKER_H
#define COOKER_H

#include <QtGui/QMainWindow>
#include "cookingclock.h"
#include <QDebug>

namespace Ui
{
    class Cooker;
}

class Cooker : public QMainWindow
{
    Q_OBJECT

public:
    Cooker(QWidget *parent = 0);
    ~Cooker();

private:
    Ui::Cooker *ui;
    CookingClock* clock;

private slots:
    void print(int);

};

#endif // COOKER_H


cooker.cpp

#include "cooker.h"
#include "ui_cooker.h"

Cooker::Cooker(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::Cooker), clock(0)
{
    ui->setupUi(this);

    clock = new CookingClock();

    connect(clock, SIGNAL(secondTicked(int)), this, SLOT(print(int)));

    clock->start();
}

Cooker::~Cooker()
{
    delete ui;
    delete clock;
}

void Cooker::print(int second)
{
    qDebug() << "second : " << second;
}

cookingclock.h

#ifndef COOKINGCLOCK_H
#define COOKINGCLOCK_H

#include <QObject>
#include <QThread>
#include <QTimer>

class CookingClock : public QThread
{
    Q_OBJECT
public:
    CookingClock(QObject *parent = 0);
    ~CookingClock();
    void stop();
    void start();

public slots:
    void countSeconds();

protected:
    virtual void run();

signals:
    void secondTicked(int);
    void timeIsUp();

private slots:
    //void countSeconds();

private:
    QTimer timer_;
    int iSeconds_;
    int iSecondsAccu_;

};

#endif // COOKINGCLOCK_H

cookingclock.cpp

#include "cookingclock.h"

CookingClock::CookingClock(QObject *parent) : QThread(parent)
        ,iSeconds_(10),iSecondsAccu_(0)
{
    timer_.setInterval(1000); //second timer

    connect(&timer_, SIGNAL(timeout()), this, SLOT(countSeconds()));

    QThread::start();
}

CookingClock::~CookingClock()
{
}

void CookingClock::run()
{
    //! Event Loop
    exec();
}

void CookingClock::countSeconds()
{
    iSecondsAccu_++;
    emit(secondTicked(iSeconds_ - iSecondsAccu_));

    if(iSecondsAccu_>=iSeconds_)
    {
        //emit(timeIsUp());
        timer_.stop();
    }
}

void CookingClock::stop()
{
    if(timer_.isActive())
    {
        timer_.stop();
    }
}

void CookingClock::start()
{
    iSecondsAccu_ = 0;
    timer_.start();
}

I'm sorry to have included so much code but I'm at my wits end even after 
trawling though several examples.

-- 
Regards,
Phil



More information about the Qt-interest-old mailing list