Qt学习记录Day2

QT自定义信号和槽,就类似于Winform中自定义委托和事件,首先自定义一个委托,委托托管一个方法,然后通过事件触发这个方法。在qt里面也是一样的。下面通过一个具体的例子学习一下,比如有一个teache类和一个student类,teacher类发出我饿了的信号,学生类触发请客吃饭,触发我饿了信号的条件就是下课了,下面看一下代码具体实现。

首先创建teache类和一个student类,他们都继承QObject。在teache头问价里面创建一个信号,我饿了

#ifndef TEACHER_H
#define TEACHER_H

#include <QObject>

class Teacher : public QObject
{
    Q_OBJECT
public:
    explicit Teacher(QObject *parent = 0);

signals:
    void woerle();//创建一个信号

public slots:

};

#endif // TEACHER_H

在student头文件里面创建一个槽函数,请你吃饭,student类必须实现槽函数。

#ifndef STUDENT_H
#define STUDENT_H

#include <QObject>

class Student : public QObject
{
    Q_OBJECT
public:
    explicit Student(QObject *parent = 0);

signals:

public slots:
   void qingnichifan();
};

#endif // STUDENT_H
#include "student.h"
#include<QDebug>
#include<QMessageBox>
Student::Student(QObject *parent) :
    QObject(parent)
{
}
void Student::qingke(){
    QMessageBox message(QMessageBox::NoIcon, "Title", "Content with icon.");

    message.exec();

}

然后在主函数得头文件中创建老师和学生类得指针。

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include<QPaintEvent>
#include "teacher.h"
#include "student.h"
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    Teacher *tc;  //创建老师学生指针
    Student *st;
    void chuf();  //触发信号得函数

private:
    Ui::MainWindow *ui;

private slots:
    void dff();
protected:
    void paintEvent(QPaintEvent *event) override;
};
#endif // MAINWINDOW_H
 this->tc=new Teacher();
    this->st=new  Student();
    connect(tc,&Teacher::hugu,st,&Student::qingke);
    chuf();
//触发信号得函数  用emit触发
void MainWindow::chuf(){
    emit tc->hugu();
}

关于信号和槽得重载,定义好重载得信号和槽,在主函数实例化得时候修改一下连接函数

 this->tc=new Teacher();
    this->st=new  Student();
    void(Teacher::*tdd)(QString)=&Teacher::woerle;
     void(Student::*sdd)(QString)=&Student::qingnichifan;
    connect(tc,tdd,st,sdd);

触发得时候将重载得值传入进去就可以了。

猜你喜欢

转载自blog.csdn.net/qq_40098572/article/details/128929022
今日推荐