zoukankan      html  css  js  c++  java
  • 自定义信号和槽

    student.h

     1 #ifndef STUDENT_H
     2 #define STUDENT_H
     3 
     4 #include <QObject>
     5 
     6 class Student : public QObject
     7 {
     8     Q_OBJECT
     9 public:
    10     explicit Student(QObject *parent = 0);
    11 
    12 signals:
    13 
    14 public slots:
    15     //早期Qt版本,必须要写道public slots 下高级版本可以写道public或者全局下
    16     //返回值 void ,需要声明 , 也需要实现
    17     //可以有参数,可以发生重载
    18     void treat();
    19 };
    20 
    21 #endif // STUDENT_H

    teacher.h

     1 #ifndef TEACHER_H
     2 #define TEACHER_H
     3 #include <QObject>
     4 
     5 class Teacher : public QObject
     6 {
     7     Q_OBJECT
     8 public:
     9     explicit Teacher(QObject *parent = 0);
    10 
    11 signals:
    12     //自定义信号  写到signals下
    13     //返回值是void , 只需要声明  , 不需要实现
    14     //可以有参数 , 可以有重载
    15     void hungry();
    16 
    17 public slots:
    18 };
    19 
    20 #endif // TEACHER_H

    widget.h

     1 #ifndef WIDGET_H
     2 #define WIDGET_H
     3 #include "teacher.h"
     4 #include "student.h"
     5 #include <QWidget>
     6 
     7 class Widget : public QWidget
     8 {
     9     Q_OBJECT
    10 
    11 public:
    12     Widget(QWidget *parent = 0);
    13     ~Widget();
    14 private:
    15     //对  对象以及下课 方法进行声明
    16     Teacher *lz;
    17     Student *jj;
    18     void classIsOver();
    19 
    20 };
    21 
    22 #endif // WIDGET_H

    student.cpp

     1 #include "student.h"
     2 #include "QDebug"
     3 Student::Student(QObject *parent) : QObject(parent)
     4 {
     5 
     6 }
     7 //对声明的请客方法进行实现
     8 void Student::treat()
     9 {
    10     //可以用qDebug方法 输出一句话
    11     qDebug()<<"请老师吃饭";
    12 }

    teacher.cpp

    1 #include "teacher.h"
    2 
    3 Teacher::Teacher(QObject *parent) : QObject(parent)
    4 {
    5 
    6 }

    widget.cpp

     1 #include "widget.h"
     2 
     3 Widget::Widget(QWidget *parent)
     4     : QWidget(parent)
     5 {
     6     //创建老师和学上对象  其中 new Teacher(this) 中的this 指对象是widget 的子类 
     7     this->lz = new Teacher(this);
     8     this->jj = new Student(this);
     9     //老师饿了学生请吃饭 信号槽的连接
    10     connect(lz,&Teacher::hungry,jj,&Student::treat);
    11     //调用 下课 方法  触发信号
    12     classIsOver();
    13 
    14 }
    15 
    16 Widget::~Widget()
    17 {
    18 
    19 }
    20 void Widget ::classIsOver()
    21 {
    22     // emit 可以用来触发信号
    23     emit lz->hungry();
    24 }
  • 相关阅读:
    大型运输行业实战_day12_1_权限管理实现
    大型运输行业实战_day11_2_事务理论与实际生产配置事务管理
    大型运输行业实战_day11_1_aop理论与aop实际业务操作
    SpringBoot目录文件结构和官方推荐的目录规范、静态资源访问
    SpringBoot常用的注解
    Spring Boot面试题
    Spring常见面试题总结
    dubbo面试题及答案
    nginx面试题及答案
    Mybatis面试题及答案
  • 原文地址:https://www.cnblogs.com/liuxjie/p/12176341.html
Copyright © 2011-2022 走看看