情景(需求)抽象:
A类对象是B类对象的成员变量。
B类对象是A类对象的父亲。
A类对象中包含按钮,点击按钮,调用B类的成员函数。
示例:
A类:
#pragma once#include <QWidget>
#include "ui_QtWidgetsClass.h"class QtWidgetsClass : public QWidget
{Q_OBJECTpublic:QtWidgetsClass(QWidget *parent = nullptr);~QtWidgetsClass();void yyy();
private:Ui::QtWidgetsClassClass ui;
};
#include "QtWidgetsClass.h"
#include "QtWidgetsApplication1.h"
QtWidgetsClass::QtWidgetsClass(QWidget *parent): QWidget(parent)
{ui.setupUi(this);connect(ui.pushButton, &QPushButton::clicked, this, &QtWidgetsClass::yyy);
}QtWidgetsClass::~QtWidgetsClass()
{
}
void QtWidgetsClass::yyy()
{QtWidgetsApplication1* w = (QtWidgetsApplication1*)(this->parent());w->xxx();
}
B类:
#pragma once#include <QtWidgets/QMainWindow>
#include "ui_QtWidgetsApplication1.h"class QtWidgetsClass;
class QtWidgetsApplication1 : public QMainWindow
{Q_OBJECTpublic:QtWidgetsApplication1(QWidget *parent = nullptr);~QtWidgetsApplication1();void xxx();
private:Ui::QtWidgetsApplication1Class ui;QtWidgetsClass* c;
};
#include "QtWidgetsApplication1.h"
#include "QtWidgetsClass.h"
#include <qdebug.h>
QtWidgetsApplication1::QtWidgetsApplication1(QWidget *parent): QMainWindow(parent)
{ui.setupUi(this);c = new QtWidgetsClass(this);
}QtWidgetsApplication1::~QtWidgetsApplication1()
{
}
void QtWidgetsApplication1::xxx()
{qDebug() << "QtWidgetsApplication1::xxx()";
}
main.cpp:
#include "QtWidgetsApplication1.h"
#include <QtWidgets/QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);QtWidgetsApplication1 m;m.show();return a.exec();
}
效果:点击按钮,对象c调用其parent对象m的xxx()函数。
进一步拓展,当有多重嵌套时,也可使用该方法。
QtWidgetsApplication1* w = (QtWidgetsApplication1*)(this->parent());
不断获取parent(),然后调用相关函数。