手动实现对象树模型:
#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()
{
cout<<"================"<<endl;
B b; //实例化b这个控件
A *a = new A( &b ); //此时a依附于b
return 0;
}
创建一个项目,提供三个按钮,第一个按钮实现播报第二个按钮的内容,播报结束后,设置自己不可用。第二个按钮的内容是关闭,实现功能是关掉整个项目,第三个按钮功能是将第一个按钮设置为可以状态
wigget.cpp:
#include "widget.h"
#include<QDebug>
#include <QTextToSpeech>
//#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
//, ui(new Ui::Widget)
{
this->resize (1024,768);
this->setMaximumSize (1500,1000);
this->setMinimumSize (500,200);
//设置窗口标题
this->setWindowTitle ("我的窗口");
//获取标题
QString title = this->windowTitle ();
qDebug()<<title;
//设置背景颜色
this->setBackgroundRole (QPalette::Mid);
//设置允许改变背景
this->setAutoFillBackground (true);
btnl = new QPushButton(" 显示",this);
btnl->resize(100,50);
// btnl->move(200,200);
btnl->move (width ()/2,height ()/2);
btnl1 = new QPushButton("关闭",this);
btnl1->resize(100,50);
btnl1->move(btnl->width ()+width()/2,height ()/2);
btnl2 = new QPushButton("复用",this);
btnl2->resize(100,50);
btnl2->move(btnl->width ()+width()/2+btnl1->width (),height ()/2);
//qt4版本的连接
//connect (btnl,SIGNAL (clicked()),this,SLOT(showmsg()));
//lamda 表达式
/*
connect(btnl2,&QPushButton::clicked ,[&]()
{
emit signal_1();
});
connect (this,&Widget::signal_1,this,&Widget::say_msg);
*/
//qt5版本的connect连接
connect(btnl,&QPushButton::clicked,this,&Widget::say_msg );
connect (btnl1,&QPushButton::clicked ,this,&Widget::close_msg);
connect (btnl2,&QPushButton::clicked,this,&Widget::reuse_msg );
/*
connect(btnl,&QPushButton::clicked ,[&]()
{
btnl2->setText ("abcdefghijklmn");
});
*/
//移动位置
// this->move(500,50);
//输出宽度和高度
qDebug()<<"width = "<<this->width ()<<" height = "<<this->height ();
//输出坐标点
qDebug()<<"坐标点为:"<<this->x()<<","<<this->y ();
//ui->setupUi(this);
}
Widget::~Widget()
{
//delete ui;
}
void Widget::showmsg()
{
static int i = 1;
this->btnl2->setText(QString::number (i++));
// this->btnl1->setText("111111");
speech.say(btnl2->text ());
btnl1->setEnabled (false);
}
void Widget::say_msg()
{
speech.say(btnl1->text());
btnl->setEnabled (false);
}
void Widget::close_msg()
{
close ();
}
void Widget::reuse_msg()
{
btnl->setEnabled (true);
}