PDA

View Full Version : Use connect() to a Qt terminal application?



hakermania
26th December 2010, 23:26
#include <stdlib.h>
#include <QtCore/QTimer>

void check(){
//perform a check every 10 secs
}

int main()
{
QTimer *timer = new QTimer;
connect(timer, SIGNAL(timeout()), this, SLOT(check()));
timer->start(10000)
return 0;
}
Ok, this is the code.... i get error that connect() wasn't declared over here :/
What Qt library should I include to use connect() function? Thank you!

squidge
26th December 2010, 23:39
I believe 'connect' is part of QObject, but I doubt it'll work without a QApplication.

AlexSudnik
27th December 2010, 06:29
Hey,

Right,first off you have to initiate a QApplication object (for event dispatching,application initialization,etc. look at the Assistant for full info).

Then,it's not quite clear what you're trying to get connected.I mean if the code's snippet you provided is the main() program function then...what is "this" then? THere are two "types" of timers available:

1.Event-driven timer (look at the int QObject::startTimer(int) )

2.QTimer signals

There's a great explanation of both in Assistant,so check it out...

If you're using connect outside the class (let's say in the main(int argc,char* argv[]) function),you should use the static version of it:

Qobject::connect(...);

hakermania
27th December 2010, 17:55
Thx for the replies, I really appreciate it! :)

nroberts
27th December 2010, 20:01
#include <stdlib.h>
#include <QtCore/QTimer>

void check(){
//perform a check every 10 secs
}

int main()
{
QTimer *timer = new QTimer;
connect(timer, SIGNAL(timeout()), this, SLOT(check()));
timer->start(10000)
return 0;
}
Ok, this is the code.... i get error that connect() wasn't declared over here :/
What Qt library should I include to use connect() function? Thank you!

What you're trying to do, the way you're trying to do it, is not possible in Qt. Beyond what others have stated, that you need a QApplication, the Qt signal/slot mechanism unfortunately doesn't work the way you're trying to use it. All Qt slots must be member functions within an object that inherits from QObject and uses the Q_OBJECT macro. You can't connect free functions to Qt signals like you can with other signal/slot mechanisms (like boost or GTKmm).

You CAN call the connect function from outside of any Qt object though:


int main()
{
... setup ...
QObject::connect(timer, SIGNAL(timeout()), ptr_to_object_containing_check, SLOT(check()));
...
}

Thus, fixing your code might resemble something like so:



#include <QtCore/QTimer>
#include <QCoreApplication>
#include <QObject>

class checker : public QObject
{
Q_OBJECT
public:
checker(QObject * o = 0) : QObject(o) {}

public slots:
void check() { ... }
};

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTimer * timer = new QTimer;
QObject::connect(timer, SIGNAL(timeout()), new checker(timer), SLOT(check()));
timer->start(10000);
return a.exec();
}