QT-訊號和參函式的細節用法
阿新 • • 發佈:2022-03-31
檔案目錄
Teacher.h
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
signals:
void hungry(QString foodName);
void hungry();
};
#endif // TEACHER_H
teacher.cpp
是訊號,不需要實現
student.h
#ifndef STUDENT_H #define STUDENT_H #include <QObject> #include <QString> class Student : public QObject { Q_OBJECT public: explicit Student(QObject *parent = nullptr); signals: public slots: // void 返回值型別,需要宣告和實現 // 可以有引數,可以發生過載 void say(); void say(QString foodName); }; #endif // STUDENT_H
student.cpp
#include "student.h" #include <QDebug> Student::Student(QObject *parent) : QObject(parent) { } void Student::say() { qDebug() << "Go Away!"; } void Student::say(QString foodName) { // QString先轉QByteArray,然後轉Char * qDebug() << "eat " << foodName.toUtf8().data(); }
mainwindows.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setFixedSize(200, 100);
QPushButton * buttonTech = new QPushButton;
buttonTech->resize(80, 40);
buttonTech->setText("class over");
buttonTech->move(100, 10);
buttonTech->setParent(this);
this->tea = new Teacher(this); // C++建立物件方式,h檔案宣告,C檔案指標new
this->stu = new Student(this);
// 函式過載,無參,不知道呼叫哪個地址的同名函式
//connect(tea, &Teacher::hungry, stu, &Student::say);
// 函式過載,有參,定義函式指標,指向類內函式的地址
void(Teacher:: *teaSingal)(QString) = &Teacher::hungry;
void(Student:: *stuSlot)(QString) = &Student::say;
connect(tea, teaSingal, stu, stuSlot); // 老師hungry訊號和學生say槽函式連線
classIsOver(); // 發射老師hungry訊號
// 按鈕觸發槽函式, 第三個引數,訊號的接受者是當前視窗類,並觸發視窗的槽函式
// 按鈕觸發的訊號和這個視窗的classIsOver函式相連線,這個函式傳送emit hungry訊號
connect(buttonTech, &QPushButton::clicked, this, &MainWindow::classIsOver);
// 無引數的訊號和槽連線
void(Teacher:: *teaSingalN)(void) = &Teacher::hungry;
void(Student:: *stuSlotN)(void) = &Student::say;
connect(tea, teaSingalN, stu, stuSlotN);
classIsOver(); // 發射老師hungry訊號
// 訊號和訊號的連線
QPushButton * button = new QPushButton("signal", this);
button->resize(50, 50);
button->move(0, 0);
connect(button, &QPushButton::clicked, stu, stuSlotN);
// 訊號斷開, 上一行程式碼的connect,無效了
disconnect(button, &QPushButton::clicked, stu, stuSlotN);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::classIsOver()
{
emit tea->hungry("asd");
emit tea->hungry();
}