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");
}
相关推荐
CHQIUU1 小时前
使用 CDN 在国内加载本地 PDF 文件并处理批注:PDF.js 5.x 实战指南
开发语言·javascript·pdf
钢铁男儿1 小时前
C# 方法(引用类型作为值参数顸引用参数)
开发语言·c#
明月看潮生1 小时前
青少年编程与数学 02-019 Rust 编程基础 02课题、开始编程
开发语言·算法·青少年编程·rust·编程与数学
yuanManGan1 小时前
C++入门小馆 :多态
开发语言·c++
冰激凌zz1 小时前
ubuntu nobel + qt5.15.2 设置qss语法识别正确
linux·qt·ubuntu
坐吃山猪1 小时前
Python-JsonRPC
开发语言·python
小毛驴8501 小时前
Windows环境,Python实现对本机处于监听状态的端口,打印出端口,进程ID,程序名称
开发语言·windows·python
MyhEhud1 小时前
Kotlin zip 函数的作用和使用场景
开发语言·windows·kotlin
火龙谷1 小时前
【工具推荐】Code2Prompt
开发语言
code monkey.2 小时前
【探寻C++之旅】第十三章:红黑树
开发语言·数据结构·c++