Qt使用信号和槽实现窗体间的传值

思路:创建两个窗体:dialog、widget。实现dialog 发送信息给widget窗体。

在dailog类中定义一个signals: void sendData(QString);

在widget中定义一个private slots:void receiveData(QString data);

在widget窗体中实例化一个dialog的对象,显示dialog窗体,并连接信号和槽。主函数中显示widget的窗体

测试代码::将通过点击dialog按钮实现dialog的lineEdit的文字信息在widget中的lineEdit显示
signal_slot.pro

#-------------------------------------------------
#
# Project created by QtCreator 2019-03-21T14:49:53
#
#-------------------------------------------------

QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = slot_signal
TEMPLATE = app
SOURCES += main.cpp\
        dialog.cpp \
    form.cpp
HEADERS  += dialog.h \
    form.h
FORMS    += dialog.ui \
    form.ui

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include 

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

private slots:
    void on_pushButton_clicked();
signals:
    void sendData(QString);   //用来传递数据的信号

private:
    Ui::Dialog *ui;
};

#endif // DIALOG_H

form.h

#ifndef FORM_H
#define FORM_H

#include 

namespace Ui {
class Form;
}

class Form : public QWidget
{
    Q_OBJECT

public:
    explicit Form(QWidget *parent = 0);
    ~Form();

private slots:
    void receiveData(QString data);   //接收传递过来的数据的槽

private:
    Ui::Form *ui;
};

#endif // FORM_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"


Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);


}

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

void Dialog::on_pushButton_clicked()
{
    sendData(ui->lineEdit->text());
}

form.cpp

#include "form.h"
#include "ui_form.h"
#include "dialog.h"

Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);


    Dialog *dlg = new Dialog;
    dlg->show();
    //关联信号和槽函数
    connect(dlg, SIGNAL(sendData(QString)), this, SLOT(receiveData(QString)));
}

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

void Form::receiveData(QString data)
{
    ui->lineEdit->setText(data);
}

main.cpp

#include "form.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Form f;
    f.show();

    return a.exec();
}

你可能感兴趣的:(OpenCV)