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"//声名student


QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class School;
class Student;

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    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;
}

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

下课

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值