手动实现对象树模型
实现代码
#include <iostream>
#include<list>
using namespace std;
class ObjTree
{
private:
list<ObjTree *> childList; //存放子对象的指针链表
public:
ObjTree(ObjTree *parent = nullptr) {
if(parent != nullptr)
parent->childList.push_back(this);
}
virtual ~ObjTree()
{
for (auto it=childList.begin(); it!=childList.end(); ++it) {
delete *it;
}
}
list<ObjTree *> & child()
{
return childList;
}
};
//定义子类
class A:public ObjTree
{
public:
A(ObjTree *parent = nullptr)
{
if(parent != nullptr)
{
parent->child().push_back(this);
}
cout<<"A::构造函数"<<endl;
}
virtual ~A()
{
cout<<"A::析构函数"<<endl;
}
};
class B:public ObjTree
{
public:
B(ObjTree *parent = nullptr)
{
if(parent != nullptr)
{
parent->child().push_back(this);
}
cout<<"B::构造函数"<<endl;
}
virtual ~B()
{
cout<<"B::析构函数"<<endl;
}
};
int main()
{
B b; //实例化b这个控件
A *a = new A( &b ); //此时a依附于b
return 0;
}
运行结果
创建一个项目,提供三个按钮
第一个按钮实现播报第二个按钮的内容,播报结束后,设置自己不可用。
第二个按钮的内容是关闭,实现功能是关掉整个项目。
第三个按钮功能是将第一个按钮设置为可以状态
实现代码
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
#include <QTextToSpeech>
class Widget : public QWidget
{
Q_OBJECT
public slots:
void broadcast();
public:
Widget(QWidget *parent = nullptr);
~Widget();
//定义一个指针
QPushButton *btn1;
QPushButton *btn2;
QPushButton *btn3;
//定义一个播报者
QTextToSpeech speech;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
void Widget::broadcast()
{
speech.say(btn3->text());
btn2->setEnabled(false);
}
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->resize(500,100); //重新设置主控件大小
btn1=new QPushButton("可用",this);
btn1->resize(150,50);
btn1->move(0,25);
btn2=new QPushButton("播报",this);
btn2->resize(150,50);
btn2->move(166,25);
btn3=new QPushButton("关闭",this);
btn3->resize(150,50);
btn3->move(332,25);
connect(btn3,&QPushButton::clicked,[=](){
this->close();
});
connect(btn2,&QPushButton::clicked,this,&Widget::broadcast);
connect(btn1,&QPushButton::clicked,[=](){
btn2->setEnabled(true);
});
}
Widget::~Widget()
{
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
运行结果
![](https://i-blog.csdnimg.cn/blog_migrate/5459659f2bcccf875cf8608a4ce3c440.png)
点击关闭,关闭项目
点击播报,播放关闭按钮内容,即“关闭”,
播报后,该按钮不可用
![](https://i-blog.csdnimg.cn/blog_migrate/484e0402bf32edd800c09d1097779298.png)
点击可用,播报按钮变为可用状态
![](https://i-blog.csdnimg.cn/blog_migrate/4df141ac8c52521bfff022cba0c7d3fb.png)