欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > Ubuntu中qt类与类信号槽的创建及使用

Ubuntu中qt类与类信号槽的创建及使用

2024/10/26 1:28:02 来源:https://blog.csdn.net/weixin_70293633/article/details/141753258  浏览:    关键词:Ubuntu中qt类与类信号槽的创建及使用

今天学习到了新的一个小玩意,我们在QT中创建一个大项目的时候一般会创建多个类,那我们就来学习一下如何在自定义的类中声名和使用信号与槽函数。

首先我们CTRL+n来创建我们新的类:

我们创建新的C++的类,一个School,一个Students。

我使用的是Cmake!!!!不是qmake!!!!!!!!

创建好之后呢,我们要先声名一下我们的两个类 ,看代码:(在mainwindow.h)

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include "school.h"//声名school
#include"student.h"//声名studentQT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACEclass School;
class Student;class MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_pushButton_clicked();private:Ui::MainWindow *ui;School *school;    //实例化Student *student;    //实例化
};
#endif // MAINWINDOW_H

然后到我们的school 类中,我们在signals:(信号)这里定义我们的信号方法

#ifndef SCHOOL_H
#define SCHOOL_H#include <QObject>class School : public QObject
{Q_OBJECT
public:explicit School(QObject *parent = nullptr);signals://信號void sendMessages();
};#endif // SCHOOL_H

同样的在student中也要定义,这里定义的是槽。

这里有个重要的知识点,就是信号只声名就可以,但是槽要声名后还要定义!!!

#include "student.h"
#include"iostream"using namespace std;
Student::Student(QObject *parent): QObject{parent}
{}void Student::comeBackToClass()
{cout << "student go to school" <<endl;
}

这里我们简单的定义一下,我们使用cout方法输出一下就好。

最后我们要在mainwindow.cpp中连接了,连接的格式如下

connect (信号, SIGNAL(你声名的信号函数) , 槽,SLOT(你声名的槽函数));

 

#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "debug/debug.h"
#include "iostream"using namespace std ;MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);school = new School(this);student = new Student(this);connect(school, SIGNAL(sendMessages()),student, SLOT(comeBackToClass()));emit school->sendMessages();}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_pushButton_clicked()
{cout << "open the clicked" <<endl;
}

 这样 我们就将两个类连接到一起了。!!!

下课

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com