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");
}
相关推荐
小小鱼儿飞2 分钟前
QT Quick QML项目音乐播放器16----无边框窗口拖动、小窗播放、隐藏系统托盘
开发语言·qt
Jay Chou why did3 分钟前
14. Qt 自定义控件
qt
-指短琴长-6 分钟前
Qt的下载和安装【Windows】
开发语言·windows·qt
不会编程的小寒7 分钟前
C++ this指针、常函数、内联函数
java·开发语言
小冯的编程学习之路11 分钟前
【C++】:C++基于微服务的即时通讯系统(2)
开发语言·c++·微服务
许长安27 分钟前
C/C++中的extern关键字详解
c语言·开发语言·c++·经验分享·笔记
earthzhang20211 小时前
【1039】判断数正负
开发语言·数据结构·c++·算法·青少年编程
蕓晨1 小时前
auto 自动类型推导以及注意事项
开发语言·c++·算法
mjhcsp2 小时前
C++ 递推与递归:两种算法思想的深度解析与实战
开发语言·c++·算法
m0_748248022 小时前
《详解 C++ Date 类的设计与实现:从运算符重载到功能测试》
java·开发语言·c++·算法