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");
}
相关推荐
mengzhi啊3 分钟前
QPluginLoader 动态 DLL 插件版,支持插件之间通信,广播。请求和应答
c++·qt
脉动数据行情115 分钟前
C# 实现德指 DAX 期货 WebSocket 实时行情监听
开发语言·websocket·c#
大圣编蚕41 分钟前
Java ByteArrayInputStream 详解:从入门到实战
java·开发语言·算法
菜鸟~noob2331 小时前
【电子战】第02篇:能量检测器 vs. 相关检测器【含matlab代码】
开发语言·matlab
OpenAnolis小助手2 小时前
一句话看透 JVM,SysOM 诊断 Skill 新增 Java 应用诊断能力
java·开发语言·jvm·阿里云·操作系统控制台·sysom
小玮看世界2 小时前
[Python]OD算法在OD实际运用转化参考清单
开发语言·python·算法
ForteScarlet2 小时前
Kotlin 2.4.20 现已发布,新特性多不多?
android·java·开发语言·开源·kotlin·jetbrains
萧瑟余晖2 小时前
Java深入解析篇六十二之安全机制详解
java·开发语言
老赵的博客3 小时前
c++ QT之动态库加载问题
c++·qt
菜鸟~noob2333 小时前
【电子战】 第01篇:噪声、门限与虚警/检测概率(PFA/PD)【含matlab代码】
开发语言·matlab