8.31嵌入式作业(对象树模型、信号与槽的连接函数)

文章目录

  • 作业内容
  • 代码部分
    • 对象树模型
    • 三个按钮
      • 头文件
      • 功能函数文件
  • 测试结果

作业内容

  1. 手动实现对象树模型
  2. 创建一个项目,提供三个按钮,第一个按钮实现播报第二个按钮的内容,播报结束后,设置自己不可用。第二个按钮的内容是关闭,实现功能是关掉整个项目,第三个按钮功能是将第一个按钮设置为可以状态

代码部分

对象树模型

#include 
#include 

using namespace std;

class ObjTree
{
    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;
    }

    ~A()
    {
        cout<<"A::析构函数"<<endl;
    }

};

class B:public ObjTree
{
public:
    B(ObjTree *parent = nullptr)
    {
        if(parent != nullptr)
        {
            parent->child().push_back(this);
        }
        cout<<"B::构造函数"<<endl;
    }

    ~B()
    {
        cout<<"B::析构函数"<<endl;
    }

};

int main()
{
    cout<<"---------------"<<endl;
    B b;        //实例化b这个控件
    A *a = new A(&b);    //此时a依附于b

    return 0;
}

三个按钮

头文件

#ifndef MYWND_H
#define MYWND_H

#include 
#include 
#include 

class MyWnd : public QWidget
{
    Q_OBJECT

public slots:
    void showMes();
    void say_mes();

public:
    MyWnd(QWidget *parent = nullptr);
    ~MyWnd();

    //定义一个按钮指针
    QPushButton *btn1;
    QPushButton *btn2;
    QPushButton *btn3;

    //定义一个播报者
    QTextToSpeech speech;

};
#endif // MYWND_H

功能函数文件

#include "mywnd.h"
#include 
#include 

void MyWnd::showMes()
{
    speech.say(btn2->text());
    btn1->setDisabled(true);
}

//处理自定义信号的槽函数
void MyWnd::say_mes()
{
    btn1->setEnabled(true);
}

MyWnd::MyWnd(QWidget *parent)
    : QWidget(parent)
{
    this->setFixedSize(500,400);       //设置固定尺寸

    //设置窗口标题
    this->setWindowTitle("作业2");

    //设置背景色
    this->setBackgroundRole(QPalette::Link);
    this->setAutoFillBackground(true);

    btn1 = new QPushButton(this);
    btn1->resize(80,30);
    btn1->setParent(this);          //设置父控件
    btn1->move(0,(this->height()-btn1->height())/2);
    btn1->setText("点击播报");

    btn2 = new QPushButton("退出",this);
    btn2->resize(80,30);
    btn2->move(btn1->width(),(this->height()-btn1->height())/2);

    btn3 = new QPushButton("重置btn1",this);
    btn3->resize(80,30);
    btn3->move(btn1->width()+btn2->width(),(this->height()-btn1->height())/2);

    connect(btn1,&QPushButton::clicked,this,&MyWnd::showMes);
    //使用Lambda表达式作槽函数
    connect(btn2,&QPushButton::clicked,[&](){
        this->close();
    });
    connect(btn3,&QPushButton::clicked,this,&MyWnd::say_mes);
}

MyWnd::~MyWnd()
{
}

测试结果

8.31嵌入式作业(对象树模型、信号与槽的连接函数)_第1张图片

你可能感兴趣的:(c++,算法,开发语言)