信号与槽函数实现
创建一个项目,提供三个按钮,第一个按钮实现播报第二个按钮的内容,播报结束后,设置自己不可用。第二个按钮的内容是关闭,实现功能是关掉整个项目,第三个按钮功能是将第一个按钮设置为可以状态
代码实现
.h头文件
#ifndef MYWND_H
#define MYWND_H
#include <QWidget>
#include<QPushButton>
#include<QtTextToSpeech>
class MyWnd : public QWidget
{
Q_OBJECT
signals:
void signal_1();
public slots:
void shoeMes();
void say_mes();
public:
MyWnd(QWidget *parent = nullptr);
~MyWnd();
QPushButton *btn1;
QPushButton *btn2;
QPushButton *btn3;
QTextToSpeech speech;
};
#endif
功能函数
#include "mywnd.h"
#include <QDebug>
void MyWnd::shoeMes(){
speech.say(btn2->text());
btn1->setEnabled(false);
}
void MyWnd::say_mes()
{
speech.say(btn2->text());
}
MyWnd::MyWnd(QWidget *parent)
: QWidget(parent)
{
this->resize(1024,768);
this->setMaximumSize(1500,1000);
this->setMinimumSize(150,100);
this->setFixedSize(1198,1102);
this->setWindowTitle("FirstWindow");
QString title = this->windowTitle();
qDebug()<<title;
this->setBackgroundRole(QPalette::Dark);
this->setAutoFillBackground(true);
this->move(50,50);
qDebug()<<"width = "<<this->width()<<"heigh = "<<this->height();
qDebug()<<"坐标点 "<<this->x()<<","<<this->y();
qDebug()<<this->pos();
btn1 = new QPushButton(this);
btn1->setParent(this);
btn1->resize(75,30);
btn1->move(0,height()/2);
btn1->setText("点击");
btn2 = new QPushButton(this);
btn2->move(btn1->width(),height()/2);
btn2->setText("关闭");
btn2->resize(btn1->size());
btn3 = new QPushButton(this);
btn3->move(btn1->width()+btn2->width(),height()/2);
btn3->resize(btn1->size());
btn3->setText("显示");
connect(btn1,&QPushButton::clicked,[&](){MyWnd::shoeMes();
});
connect(btn2,&QPushButton::clicked,[&](){MyWnd::close();
});
connect(btn3,&QPushButton::clicked,[&](){
btn1->setEnabled(true);
});
}
MyWnd::~MyWnd()
{
}
运行现象(部分)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f90e04ed094f2c07620fed73aea1940e.png)
手动实现对象树模型
代码实现
#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;
A *a = new A( &b );
return 0;
}