如图,想要实现信号和槽函数连接
mainwindow.h文件:
=================== mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include"teacher.h"
#include"student.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void classIsOver();
Teacher *ls;
Student *fz;
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
============================ student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
#include<QDebug>
#pragma once
class Student : public QObject
{
Q_OBJECT
public:
explicit Student(QObject *parent = nullptr);
void trest(QString food);
signals:
};
#endif // STUDENT_H
====================== teacher.h
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
#include<QDebug>
#pragma once
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
// void hungry2(QString food);
signals:
void hungry2(QString food);
};
#endif // TEACHER_H
============================== mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
//#include"teacher.h"
#include<QPushButton>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPushButton *mybtn = new QPushButton(0);
mybtn->setParent(this);
mybtn->QPushButton::setText("我的按钮");
mybtn->resize(200,40);
mybtn->move(100,50);
this->ls = new Teacher(this);
this->fz = new Student(this);
connect(mybtn,&QPushButton::clicked,this,&MainWindow::classIsOver);
}
void MainWindow::classIsOver(){
ls->hungry2("宫保鸡丁");
}
MainWindow::~MainWindow()
{
delete ui;
}
===================== student.cpp
#include "student.h"
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::trest(QString food){
qDebug()<<"请老师吃:"<<food<<endl;
}
========================= teacher.cpp
#include "teacher.h"
Teacher::Teacher(QObject *parent) : QObject(parent)
{
}
void Teacher::hungry2(QString food){
qDebug()<<"老师饿了,要吃:"<<food;
}
编译后一直报错
看别人写的文章说是变量、函数重定义,但是我的 hungry() 函数是在teacher.h声明,teacher.cpp
中定义的,不存在这样问题,然后发现这里连接的槽函数
connect(mybtn,&QPushButton::clicked,this,&MainWindow::classIsOver);
槽函数是 classIsOver() , classIsOver()又调用 hungry()函数,忽然想到 hungry()现在还不是信号函数,于是把teacher.h中signal:下的hungry()放到Pubilc作用域下,再次构建项目,果然不在报错,
改之前:
================== teacehr.h
#include <QObject>
#include<QDebug>
#pragma once
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
// void hungry2(QString food);
signals:
void hungry2(QString food);
};
#endif // TEACHER_H
改后:
============= teacher.h
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
#include<QDebug>
#pragma once
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
void hungry2(QString food);
signals:
// void hungry2(QString food);
};
#endif // TEACHER_H