#1. Background
In QT development, when encountering a child form, call the function of the parent form.
Generally, the parent form calls the child form, but the reverse is also possible. It can be seen that there are all kinds of programming situations.
#2. Examples
##2.1. Avoid cross-referencing
If you refer to each other, the compilation will not pass.
By declaring the class in the header file, here is the declaration:
class Dialog; This class is the parent form.
DialogSon1: This class is a child form
ifndef DIALOGSON1_H
#define DIALOGSON1_H
#include <QDialog>
namespace Ui {
class DialogSon1;
}
class Dialog;
class DialogSon1 : public QDialog
{
Q_OBJECT
public:
explicit DialogSon1(QWidget *parent = 0);
~DialogSon1();
private slots:
void on_pushButton_clicked();
private:
Ui::DialogSon1 *ui;
Dialog *m_parent;
};
#endif // DIALOGSON1_H
The method of the parent form is implemented as follows, and now I just want to realize how the child form calls this function of the parent form:
QString Dialog::getState()
{
qDebug()<<"I'm parent class, I'm eating";
QString str = "I'm parent class, I'm eating";
return str;
}
##2.2, Get the parent form through parentWidget()
Now start calling this method, first get the parent form, and call the method of the parent form:
DialogSon1::DialogSon1(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogSon1)
{
ui->setupUi(this);
m_parent = (Dialog *)parentWidget();
}
void DialogSon1::on_pushButton_clicked()
{
QString str = m_parent->getState();
ui->label->setText(str);
}
The final effect is as follows:
#3. Summary