PDA

View Full Version : QThread & QTimer



hosseinyounesi
11th April 2009, 12:58
Hi every body, I'm trying to make a window and show a time in every 1 minutes. This is what what I wrote to do that:

MyThread .h file:


class MyThread : public QThread
{
Q_OBJECT
private:
MainWindow *w;
QTimer *timer;
public:
MyThread( QObject* parent );
void run();
public slots:
void ToDo();
};


main.cpp


MainWindow mw;
MyThread::MyThread( QObject* parent ) : QThread( parent )
{
// nothing to do !!!
}

void MyThread::run()
{
mw.show();
timer = new QTimer(this);
connect(timer,SIGNAL(timeout()), this, SLOT(ToDo()));
timer->setInterval(2009);
timer->start();
return a.exec();
}
void MyThread::ToDo() {
long i=0,h=0,m=0,s=0;
while(i<3)
{
std::string str = "Time: ";
char msg[100];
Converter(gTime,h,m,s);
sprintf(msg,"%02ld:%02ld:%02ld",h,m,s);
str += msg;
w->setText(QString::fromUtf8(str.c_str(),str.size())) ;
sleep(1);
i++;
gTime--;
}
a.closeAllWindows();
}

int main()
{
MyThread mt(0);
mt.start();
mt.wait();
}


It is compiled but this is the error when I try to execute the program:



QObject: Cannot create children for a parent that is in a different thread.
(Parent is MyThread(0xbfbc4cac), parent's thread is QThread(0x80843a0), current thread is MyThread(0xbfbc4cac)


Thanks for your consideration

wysota
11th April 2009, 13:35
What is the thread for?

hosseinyounesi
11th April 2009, 15:30
mmmmmmm, I don't know !!!!!
This is what I exactly want to do:

Program starts and shows a timer for 5 seconds. Then it hides or closes and after 10 minutes shows the same. What I have to do?

I tried to make a QThread and show the mainwindow, then set a QTimer, it has to change the text of a label for a 5 second timer.

Any better way?!

wysota
11th April 2009, 19:10
You don't need the thread. The timer will let you know when a specified amount of time has passed. Here is a sample code:

#include <QApplication>
#include <QLabel>
#include <QTimer>
#include <QDateTime>

class Dummy : public QObject {
Q_OBJECT
public:
Dummy(QLabel *l) : QObject(){m_label = l; }
public slots:
void doIt(){ m_label->setText(QDateTime::currentDateTime().toString()); }
private:
QLabel *m_label;
};

#include "main.moc"

int main(int argc, char **argv){
QApplication app(argc, argv);
QLabel label;
QTimer t;
Dummy dummy(&label);
dummy.doIt();
QObject::connect(&t, SIGNAL(timeout()), &dummy, SLOT(doIt()));
t.start(1000);
label.show();
return app.exec();
}

hosseinyounesi
12th April 2009, 13:39
You are right but I want to hide the window after 10 seconds for 5 minutes then show it again. What now?

Thanks again & again & ...

Alex Snet
13th April 2009, 08:22
Uff.. The problem is solved... Thanks to all!