PDA

View Full Version : Simple QObject::connect question



Bryku
15th December 2009, 14:18
Hi. I'm new to QT and I have a good-programming-style-type problem. I want to connect 2 objects. Until now , i wrote some simple applications , and connected objects that one contains another. For example:



class c : public QWidget
{
private:
QPushButton *button;
public:
c()
{
...
connect(button,SIGNAL(signal()),this,SLOT(slot())) ;
...
}
};


And it was simple and easy.

But what if i want to connect to objects that none of them is containing another ? In "connect" i have to pass pointers to sender and reciever. Should I pass the pointer to another object in a constructor ? For example:


class ObjectA : public QWidget
{
...
public slots:
void slot();
...
};

class ObjectB : public QWidget
{
...
signals:
void signal();
public:
ObjectB(ObjectA *p)
{
...
connect(this,SIGNAL(signal()),p,SLOT(slot()));
...
}
};


Is that a good way to do that ? It works, but I believe something is wrong with that. What if i want to connect one object with twenty anothers , so i neet do pass 20 pointers in a constructor ?

jkv
15th December 2009, 15:17
Find out which higher level class in you design manages or is closest related to ObjectB and let that class code (constructor maybe?) call connect(objectB, SIGNAL(signal()), objectA, SLOT(slot())).
No need to pass 20 pointers in ctor :)

However if ObjectA itself is closely related to ObjectB (for example if you store reference to ObjectA as ObjectB member) then you might as well do as in your example...

axeljaeger
8th January 2010, 12:09
You can also connect in the next outer containing entity. For example you can connect in the main-method two object that are created there:



int main(int argc, char** argv) {
QApplication app(argc, argv);
QPushButton button("Quit");
QObject::connect(&button, SIGNAL(clicked()), &app, SLOT(quit()));
button.show();
return app.exec();
}