Qt learning record Day2

QT custom signals and slots are similar to custom delegates and events in Winform. First, you customize a delegate, the delegate hosts a method, and then triggers this method through an event. It is the same in qt. Let's learn through a specific example. For example, there is a teacher class and a student class. The teacher class sends out a signal that I am hungry, and the student class triggers a treat to eat. The condition that triggers the I am hungry signal is that class is over. Let's take a look at the specific code accomplish.

First create a teacher class and a student class, both of which inherit from QObject. Create a signal in the teache head asking price, I'm hungry

#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

Create a slot function in the student header file, invite you to dinner, the student class must implement the slot function.

#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();

}

Then create pointers to teacher and student classes in the header file of the main function.

#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();
}

Regarding the overloading of signals and slots, define the overloaded signals and slots, and modify the connection function when the main function is instantiated

 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);

Just pass in the overloaded value when it is triggered.

Guess you like

Origin blog.csdn.net/qq_40098572/article/details/128929022