PDA

View Full Version : connect between function of two differents QWidget



shenakan
9th September 2010, 10:50
I have two classes : classA and classB

I would like to connect a function F() from classB with a click event from a button ui of the classA.

I know there is the possibitlity to have the classB member of the class A. But there is another to do it if the class are separe?

The connect function shoud be in the class A connect(ui->button,SIGNAL(clicked(),b->F())); ???



class classA : public QWidget
{
Q_OBJECT

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

private:
Ui::board *ui;
};



class classB: public QWidget
{
Q_OBJECT

public:
classB(QWidget *parent = 0);
~classB();
void F();
};

tbscope
9th September 2010, 11:13
Try using slots:



class classA : public QWidget
{
Q_OBJECT

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

private:
Ui::board *ui;
classB *b;
};

classA::classA(...) : QWidget(...)
{
b = new classB(this);

connect(ui->button, SIGNAL(clicked()), b, SLOT(f()));
}



class classB: public QWidget
{
Q_OBJECT

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

public slots:
void f();
};

shenakan
9th September 2010, 16:46
Try using slots:



class classA : public QWidget
{
Q_OBJECT

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

private:
Ui::board *ui;
classB *b;
};

classA::classA(...) : QWidget(...)
{
b = new classB(this);

connect(ui->button, SIGNAL(clicked()), b, SLOT(f()));
}



class classB: public QWidget
{
Q_OBJECT

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

public slots:
void f();
};



This is the solution simplest solution. But I dont want to have the object B (from classB) membres of the classA.

I don't know if there is a solution to list all the Qwidgets present in an application to call their functions ????

saa7_go
9th September 2010, 18:32
You can create custom signal in your classA, for example buttonClicked(), that will be emitted whenever ui->button clicked() signal is emitted. So, you can connect buttonClicked() signal from classA instance to F() slot from classB instance without classB instance to be a member of classA.

Or you can create a function that return a pointer to ui->button.



class classA : public QWidget
{
Q_OBJECT
public:
classA(QWidget *parent = 0);
QPushButton *button();
~classA();

signals:
void buttonClicked();

private:
Ui::board *ui;
};

classA::classA(QWidget *parent) : QWidget(parent), ui(new Ui::board)
{
ui->setupUi(this);
connect(ui->button, SIGNAL(clicked()), this, SIGNAL(buttonClicked()));
}

QPushButton* classA::button()
{
return ui->button;
}





class classB: public QWidget
{
Q_OBJECT

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

public slots:
void F();
};




classA a;
classB b;
QObject::connect(&a, SIGNAL(buttonClicked()), &b, SLOT(F()));
// or
QObject::connect(a.button(), SIGNAL(clicked()), &b, SLOT(F()));