1.对象数模型
代码:
#include <iostream>
#include <list>
class obj;
typedef std::list<obj*> ChildList;
using namespace std;
class obj
{
public:
ChildList childen;
obj(obj *parent=nullptr) {
if(parent !=nullptr)
{
parent->childen.push_back(this);
}
}
virtual ~obj() {
//把所有子组件全部释放空间
for(auto it=childen.begin();it!=childen.end();it++)
{
delete *it;
}
}
};
//定义子类
class A:public obj
{
public:
A(obj *parent=nullptr) {
if(parent!=nullptr)
{
parent->childen.push_back(this);
}
cout<<"A::construct"<<endl;
}
~A() {
cout<<"A::xigou"<<endl;
}
};
class B:public obj
{
public:
B(obj *parent=nullptr) {
if(parent!=nullptr)
{
parent->childen.push_back(this);
}
cout<<"B::construct"<<endl;
}
~B() {
cout<<"B::xigou"<<endl;
}
};
int main()
{
A a;
B *b = new B(&a); //组件b依附于组件a而存在
return 0;
}
结果:
2.信号与槽函数
源文件:
#include "mywid.h"
#include "mywid.h"
#include<QDebug>
#include<QPushButton>//按钮类头文件
mywid::mywid(QWidget *parent)
: QWidget(parent)
{
this->setWindowTitle("my first windows");
//第一种使用方式,类似cout
qDebug()<<this->windowTitle();
//第二种方式,类似printf
qDebug("%d\t%d\n",520,1314);
//设置窗口大小
this->setMaximumSize(1024,768);//设置窗口最大尺寸
this->setMinimumSize(500,300);//设置最小窗口
this->resize(1000,1000);//重新设置大小
//this->setFixedSize(800,600);//设置固定大小
//this->move(30,30);//移动窗口位置
//this->setWindowFlag(Qt::FramelessWindowHint);//设置窗口洁净
//this->setWindowOpacity(0.7);//设置窗口透明度
//QPushButton btn1("按钮",this);
btn1=new QPushButton("no");
btn1->resize(100,50);
btn1->setParent(this);
btn2=new QPushButton(this);
btn2->resize(btn1->size());
btn2->move(btn1->width(),0);
btn3=new QPushButton("click this",this);
btn3->resize(btn1->size());
btn3->move(0,btn1->height());
qDebug()<<btn3->x()<<","<<btn3->y();
qDebug()<<btn3->pos();
//qt5版本
connect(btn1, &QPushButton::clicked, this, &mywid::page_close);
connect(btn3, &QPushButton::clicked, this, &mywid::set_tex);
//qt4版本
connect(btn3,SIGNAL(clicked()), this, SLOT(shadow()));
}
mywid::~mywid()
{
}
void mywid::page_close()
{
this->close();
}
void mywid::set_tex()
{
btn2->setText("hello world");
}
void mywid::shadow()
{
btn1->setText("close");
}
头文件:
#ifndef MYWID_H
#define MYWID_H
#include <QWidget>
#include<QPushButton>
class mywid : public QWidget
{
Q_OBJECT
public:
mywid(QWidget *parent = nullptr);
~mywid();
public slots:
void page_close();
void set_tex();
void shadow();
private:
QPushButton *btn1;
QPushButton *btn2;
QPushButton *btn3;
};
#endif // MYWID_H
主函数:
#include "mywid.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
mywid w;
w.show();
return a.exec();
}
结果: