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");
}
相关推荐
我是小灰灰吖13 小时前
Ubuntu22.04,OpenCV 4.5.5 环境搭建
linux·qt·ubuntu
snow@li13 小时前
SpringBoot:AOP日志切面全景梳理/原理+流程+实战+避坑
java·开发语言·spring boot
Nil20813 小时前
C++ emplace_back 与 push_back 详解
开发语言·c++
clear sky .13 小时前
[freertos源码阅读]task.c任务篇
c语言·开发语言
XR12345678813 小时前
工业园区整体组网,方案对比怎么选?
开发语言·php
东东最爱敲键盘14 小时前
day9.C++多态之虚函数
开发语言·c++
码云数智-园园14 小时前
类似小鹅通的知识付费小程序平台有哪些
开发语言
snow@li14 小时前
Java:跨平台原理与JDK、JRE、JVM全景深度解析
java·开发语言·jvm
Livia要学习14 小时前
Python闭包
开发语言·jvm·python
覆东流14 小时前
2.Java程序基础
java·开发语言·后端