1、手动实现QT的对象树模型
#include <iostream>
#include <list>
using namespace std;
class ObjTree
{
public:
ObjTree(ObjTree *parent=nullptr)
{
if(parent!=nullptr){
parent->child().push_back(this);
}
}
virtual ~ObjTree()
{
for(auto it=childlist.begin();it!=childlist.end();it++){
delete *it;
}
}
list<ObjTree *> &child()
{
return childlist;
}
private:
list<ObjTree *> childlist;
};
class A:public ObjTree
{
public:
A(ObjTree *parent=nullptr)
{
if(parent!=nullptr){
parent->child().push_back(this);
}
}
~A(){}
};
class B:public ObjTree
{
public:
B(ObjTree *parent=nullptr)
{
if(parent!=nullptr){
parent->child().push_back(this);
}
}
~B(){}
};
int main()
{
A a;
B *b=new B(&a); //此时b依附于a
return 0;
}
2、创建一个项目,提供三个按钮,第一个按钮功能是将第二个按钮设置为使能状态;第二个按钮实现播报第三个按钮的内容,播报结束后,设置自己不可用;第三个按钮的内容是关闭,实现功能是关掉整个项目。
ButtonTest.h
#ifndef BUTTONTEST_H
#define BUTTONTEST_H
#include <QWidget>
#include <QTextToSpeech>
QT_BEGIN_NAMESPACE
namespace Ui { class ButtonTest; }
QT_END_NAMESPACE
class ButtonTest : public QWidget
{
Q_OBJECT
public:
ButtonTest(QWidget *parent = nullptr);
~ButtonTest();
public slots:
void do_enble();
void do_speech();
void do_close();
private:
Ui::ButtonTest *ui;
QTextToSpeech speech;
};
#endif // BUTTONTEST_H
ButtonTest.cpp
#include "buttontest.h"
#include "ui_buttontest.h"
ButtonTest::ButtonTest(QWidget *parent)
: QWidget(parent)
, ui(new Ui::ButtonTest)
{
ui->setupUi(this);
ui->SpeBtn->setEnabled(false);
connect(ui->EnBtn,&QPushButton::clicked,this,&ButtonTest::do_enble);
connect(ui->SpeBtn,&QPushButton::clicked,this,&ButtonTest::do_speech);
connect(ui->CloBtn,&QPushButton::clicked,this,&ButtonTest::do_close);
}
ButtonTest::~ButtonTest()
{
delete ui;
}
void ButtonTest::do_enble()
{
ui->SpeBtn->setEnabled(1);
}
void ButtonTest::do_speech()
{
speech.say(ui->CloBtn->text());
ui->SpeBtn->setEnabled(false);
}
void ButtonTest::do_close()
{
close();
}