新建两个类:MyWidget,NewWidget
文件MyWidget.cpp内容为:
#include "mywidget.h"
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
// QPushButton b1("b1", this);
// 内存管理,当对象被释放的时候,会将它的所有子对象都释放掉
QPushButton *b1 = new QPushButton("b1", this); //只能用new的方式
QPushButton *b2 = new QPushButton("b2", this);
b3 = new QPushButton("b3", this);
b4 = new QPushButton("b4", this);
b5 = new QPushButton("b5", this);
b3->move(200,200);
b4->move(200,0);
b1->move(100,100);
b5->move(0,100);
// Qt4的写法,用 SINGNAL 和 SLOT宏
connect(b1, SIGNAL(clicked()), this, SLOT(close()));
// Qt5的写法
// 1、信号的发送者
// 2、发送的信号: &发送者类型::发送的信号
// 3、接收者
// 4、接收者的处理函数: &接收者类型::处理函数
connect(b2, &QPushButton::clicked, this, &MyWidget::close);
// 自定义槽函数
// 1、自定义槽函数放在 slots 关键字下
// 2、槽函数返回值类型为 void
// 3、槽函数的参数要信号函数保持一致
connect(b3, SIGNAL(clicked()), this, SLOT(handleClicked()));
connect(b5, SIGNAL(clicked()), this, SLOT(newWidget()));
// 自定义信号
// 1、自定义信号函数放在 signals 关键字下
// 2、信号函数返回值是void ,函数只有声明,不需要实现
// 3、信号发射: 用 emit 关键字
connect(&nw, SIGNAL(sendSigNal()), this, SLOT(reShow()));
// Lamda表达式 C++11 的特性 -----> 匿名函数
QPushButton *b6 = new QPushButton("b6", this);
b6->move(100, 300);
// connect 使用Lamda表达式必须使用qt5的方式
// 1、匿名函数不是类的成员函数,匿名函数和外部是不通的,不能使用外部的变量
// 2、外部的可以传给匿名函数
/*常用的参数:
* [=]: 外部数据以值传递的形式传入到匿名函数内部
* [&]: 外部数据以引用形式传入到匿名函数内部
*
* 比较常用的形式:
* [this] : 将this指针传递到匿名函数匿名 ----> 在匿名函数内部可以使用this指针
*/
connect(b6, &QPushButton::clicked,
[this]()
{
static int i = 0;
if (i++ % 2 == 0)
b3->setText("123"); // this->b3->setText("123");
else
b3->setText("abc"); // this->b3->setText("abc");
});
}
void MyWidget::handleClicked()
{
static int i = 0;
if (i++ % 2 == 0)
b4->setText("123");
else
b4->setText("abc");
int x = b4->x();
int y = b4->y();
x += 50;
if (x > this->width())
{
y += 150;
x = 0;
}
if (y > this->height())
{
y = 0;
}
b4->move(x, y);
}
void MyWidget::newWidget()
{
nw.show();
this->hide(); // 当前窗口隐藏
}
void MyWidget::reShow()
{
nw.hide();
this->show();
}
文件MyWidget.h内容为:
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QPushButton>
#include "newwidget.h"
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
signals:
public slots: //自定义的槽
void handleClicked();
void newWidget();
void reShow();
private:
QPushButton *b3;
QPushButton *b4;
QPushButton *b5;
NewWidget nw;
};
#endif // MYWIDGET_H
文件NewWidget.cpp中的内容为:
#include "newwidget.h"
NewWidget::NewWidget(QWidget *parent) : QWidget(parent)
{
QPushButton *b = new QPushButton("new", this);
connect(b, SIGNAL(clicked()), this, SLOT(handleClicked()));
resize(400,400);
}
void NewWidget::handleClicked()
{
emit sendSigNal(); //发送信号用emit关键字
}
文件NewWidget.h中的内容为:
#ifndef NEWWIDGET_H
#define NEWWIDGET_H
#include <QWidget>
#include <QPushButton>
class NewWidget : public QWidget
{
Q_OBJECT
public:
explicit NewWidget(QWidget *parent = 0);
signals: //自定义的信号
void sendSigNal();
public slots:
void handleClicked();
};
#endif // NEWWIDGET_H