zoukankan      html  css  js  c++  java
  • 初见QT---信号和槽(二)

    带参数的自定义信号和槽

    举例分析:响铃后,老师需要发出下课的信号,并且要带有放学参数,学生才能做出离开教室的反应

    首先在teacher.h文件下重载信号函数

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

    然后在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 = nullptr);
    11 
    12 signals:
    13 
    14 public slots:
    15     void leaveclass();
    16     //声明  重载函数
    17     void leaveclass(QString leavesignal);
    18 };
    19 
    20 #endif // STUDENT_H    

    其次在student.cpp下实现槽函数的功能

     1 #include "student.h"
     2 #include <QDebug>
     3 student::student(QObject *parent) : QObject(parent)
     4 {
     5 }
     6 void student::leaveclass(QString leavesignal)
     7 {
     8     //QString  ->char *    先转QByteArray (.tuUtf8) 再转 char *
     9     qDebug()<<"老师说"<<leavesignal.toUtf8().data();
    10 }

    最后在widget.cpp下连接信号和槽

     1 #include "widget.h"
     2 
     3 //Teacher类
     4 //Student类
     5 //铃声响了,老师发出下课的信号,学生接收信号做出离开教室的反应
     6 
     7 Widget::Widget(QWidget *parent)
     8     : QWidget(parent)
     9 {
    10     this->zt=new teacher(this);
    11     this->st=new student(this);
    12     //连接  带参数的信号和槽
    13     //指针  ->   地址
    14     //函数指针  ->   函数地址
    15     void (teacher:: *teachersignal)(QString)=&teacher::classover;
    16     void (student:: *studentsignal)(QString)=&student::leaveclass;
    17     connect(zt,teachersignal,st,studentsignal);
    18     classringing();
    19 }
    20 
    21 void Widget::classringing()
    22 {
    23     emit zt->classover("放学了");
    24 }
    25 
    26 Widget::~Widget()
    27 {
    28 }

    成果展示

  • 相关阅读:
    【转】CUDA5/CentOS6.4
    【转】centos 6.4 samba 安装配置
    【转】Install MATLAB 2013a on CentOS 6.4 x64 with mode silent
    【转】Getting xrdp to work on CentOS 6.4
    【VLFeat】使用matlab版本计算HOG
    Unofficial Windows Binaries for Python Extension Packages
    March 06th, 2018 Week 10th Tuesday
    March 05th, 2018 Week 10th Monday
    March 04th, 2018 Week 10th Sunday
    March 03rd, 2018 Week 9th Saturday
  • 原文地址:https://www.cnblogs.com/GaJack/p/12933596.html
Copyright © 2011-2022 走看看