Qt中connect函数(信号与槽)初识

Qt开发信号与槽:

一、介绍

信号槽机制与Windows下消息机制类似,消息机制是基于回调函数,Qt中用信号与槽来代替函数指针,使程序更安全简洁。信号和槽机制是 Qt 的核心机制,可以让编程人员将互不相关的对象绑定在一起,实现对象之间的通信

二、具体介绍:

信号介绍:当对象改变其状态时,信号就由该对象发射 (emit) 出去,而且对象只负责发送信号,它不知道另一端是谁在接收这个信号。这样就做到了真正的信息封装,能确保对象被当作一个真正的软件组件来使用

槽介绍:用于接收信号,而且槽只是普通的对象成员函数。一个槽并不知道是否有任何信号与自己相连接。而且对象并不了解具体的通信机制

连接介绍:信号和槽通过connect建立连接

connect使用:

connect(sender, SIGNAL(signal), receiver, SLOT(slot));

sender和receiver是对象的指针,SIGNAL和SLOT后是信号和槽相应的函数

四、具体使用:

第一个界面:

Widget类头文件:

#include <QWidget>
#include "form.h"
#include <QtWidgets>
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
signals:
    void send(QString str);
private slots:
    void clickButton();

private:
    Ui::Widget *ui;
    QLineEdit * input ;
    Form * form;

};

Widget类实现:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setGeometry(100,100,400,400);
    this->setWindowTitle(QObject::tr("Login"));
    //Label
    QLabel * label = new QLabel(this);
    label->setText(QObject::tr("请输入:"));
    label->setGeometry(50,150,70,25);
    QFont fontLabel;
    fontLabel.setPointSize(15);
    label->setFont(fontLabel);
    //Line
    this->input = new QLineEdit(this);

    this->input->setGeometry(120,150,200,25);
    QString inputString = this->input->text();
    //Button
    QPushButton * buttonLg = new QPushButton(this);
    buttonLg->setGeometry(150,200,80,30);
    buttonLg->setText("Submit");


    QObject::connect(buttonLg,&QPushButton::clicked,this,&Widget::clickButton);
    form = new Form();
    QObject::connect(this,&Widget::send,form,&Form::receive);

}
void Widget::clickButton(){
    QString str = this->input->text();
    emit send(str);

}
Widget::~Widget()
{
    delete ui;
}

第二个界面:

Form类头文件:


#include <QWidget>
#include<QLabel>

namespace Ui {
class Form;
}

class Form : public QWidget
{
    Q_OBJECT

public:
    explicit Form(QWidget *parent = 0);
    ~Form();
public slots:
    void receive(QString str);

private:
    Ui::Form *ui;
    QLabel * label;
};

Form类实现:

#include "form.h"
#include "ui_form.h"
#include <QtWidgets>
Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);
    this->setGeometry(100,100,400,400);
    this->setWindowTitle(QObject::tr("Login"));
    //Label
    label = new QLabel(this);
    label->setText("");
    label->setGeometry(50,150,170,25);
    QFont fontLabel;
    fontLabel.setPointSize(15);
    label->setFont(fontLabel);
}

Form::~Form()
{
    delete ui;
}

void Form::receive(QString str)
{
    this->label->setText(tr(" 获取的是:%1").arg(str));
    this->show();
}


猜你喜欢

转载自blog.csdn.net/guozirong123/article/details/73044742