Qt自定义信号

1.Teacher类下定义信号signals:

Student类下定义槽函数:

Teacher.h

#pragma once

#include <QObject>

class Teacher  : public QObject
{
	Q_OBJECT

public:
	Teacher(QObject *parent);
	~Teacher();
signals:
	void Ask();  //老师向学生提问
	void Ask(QString str);
};

Teacher.cpp

#include "Teacher.h"

Teacher::Teacher(QObject *parent)
	: QObject(parent)
{}

Teacher::~Teacher()
{}

Student.h

#pragma once

#include <QObject>

#include <QDebug>
#include <QMessageBox>

class Student  : public QObject
{
	Q_OBJECT

public slots:
	void Answer();
	void Answer(QString str);
public:
	Student(QObject *parent);
	~Student();
};

Student.cpp

#include "Student.h"

Student::Student(QObject *parent)
	: QObject(parent)
{}

Student::~Student()
{}

void Student::Answer()
{
    QMessageBox::information(NULL, "Message", "student answer the question",QMessageBox::Ok|QMessageBox::Cancel);
  
}

void Student::Answer(QString str)
{
    QMessageBox::information(NULL, "Message", str+": Answer Is OK", QMessageBox::Ok | QMessageBox::Cancel);

}

QSingalSlot.h

#include "ui_QSingalSlot.h"

#include "Teacher.h"
#include "Student.h"

class QSingalSlot : public QWidget
{
    Q_OBJECT

public:
    QSingalSlot(QWidget *parent = nullptr);
    ~QSingalSlot();

    Teacher* tech;
    Student* stud;
public slots:
    void AskQuestion();

private:
    Ui::QSingalSlotClass ui;
};

QSingalSlot.cpp

#include "QSingalSlot.h"

QSingalSlot::QSingalSlot(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    this->tech=new Teacher(nullptr);
    this->stud=new Student(nullptr);

    //函数指针
    void (Teacher:: * teachSignal)(QString) = &Teacher::Ask;
    void (Student:: * studentSlot)(QString) = &Student::Answer;

   // connect(tech, SIGNAL(Teacher::Ask()), stud, SLOT(Student::Answer()));  //写法调用不了
   // connect(tech, &Teacher::Ask, stud, &Student::Answer);
    connect(tech, teachSignal, stud, studentSlot);
    connect(ui.pushButton_Ask, SIGNAL(clicked()), this, SLOT(AskQuestion()));
}

QSingalSlot::~QSingalSlot()
{}

void QSingalSlot::AskQuestion()
{
    //emit tech->Ask();
    emit tech->Ask("yes or ok");
}
相关推荐
wjs20242 分钟前
R 绘图 - 饼图
开发语言
buyue__2 分钟前
Kotlin/Android中执行HTTP请求
android·开发语言·kotlin
Jerry_正弦2 分钟前
Kotlin模仿Rxjava进行数据的流式转换实现
开发语言·kotlin·rxjava
向宇it9 分钟前
【unity实战】使用Unity实现动作游戏的攻击 连击 轻重攻击和打击感
开发语言·游戏·unity·游戏引擎
叶孤程20 分钟前
【Qt知识】window frame 对窗口坐标的影响
数据库·qt·microsoft
ZJ_.23 分钟前
Node.js 使用 gRPC:从定义到实现
java·开发语言·javascript·分布式·rpc·架构·node.js
阿龍178730 分钟前
Qt中udp指令,大小端,帧头帧尾实际示例
网络·c++·qt·网络协议·udp
concisedistinct42 分钟前
大数据开发语言 Scala(四):面向对象编程
大数据·开发语言·后端·scala·编程语言·面向对象
_Rookie._1 小时前
java 单例模式
java·开发语言·单例模式