新建兩個類: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