发出来自另一个类的信号

Emit a signal from another class

本文关键字:信号 另一个      更新时间:2023-10-16

我有这段代码,由 2 个 *.cpp 个文件和 2 个 *.h 文件组成,我根本不明白如何将信号从一个类发送到另一个类:

我有主窗口.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "serialcommunication.h"
#include "QDebug"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//other functions;
}
MainWindow::~MainWindow()
{
delete ui;
//Here is where I want to emit the signal
qDebug() << "DONE!";
}

这是主窗口的标头.cpp:

class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_connectButton_clicked();
private:
Ui::MainWindow *ui;
};

所以,我想从主窗口类向串行通信类发送一个信号,在这里调用一个函数:

第二个*.cpp文件:串行通信.cpp

#include "serialcommunication.h"
#include "mainwindow.h"
SerialCommunication::SerialCommunication(QObject *parent) : QObject(parent)
{   
isStopReadConsoleActivated = false;

QtConcurrent::run(this,&SerialCommunication::readConsole,isStopReadConsoleActivated);
}
void FUNCTION THANT I WANT TO BE CALLED FROM MAINWINDOW CLASS()
{
//DO SOMETHING
}

和串行通信标头

class SerialCommunication : public QObject
{
Q_OBJECT
private:
//some other fucntions
public:
explicit SerialCommunication(QObject *parent = nullptr);
~SerialCommunication();
};

我需要在哪里放置插槽、信号和连接方法?多谢!

首先,您需要了解有关插槽信号的基本理论,它们是QT的功能。它们允许任何对象,从QOBJECT固有,在它们之间发送消息,如事件。

  1. 发出事件的类必须实现一个signal
//Definition into the Class A (who emits)
signals:
void valueChanged(int newValue);
  1. 将接收事件(信号)的类必须实现一个公共slot,该必须具有与signal相同的参数。

//Definition into the Class B (who receives)
public slots:
void setValue(int newValue);
  1. 将接收事件(信号)的类必须连接信号插槽。使用connect方法链接来自类 A 类和实例的信号,以及来自类 B 实例的插槽。

//There is an instance of class A called aEmit.
void B::linkSignals()
{
connect(&aEmit, SIGNAL(valueChanged(int)), this, SLOT(setValue(int)));
}
  1. 要触发信号,请使用关键字emit将信号作为函数及其参数:。
//from Class A
void A::triggerSignal()
{
int myValue{23};
emit valueChanged(myValue);
}
  1. 在B类中,应调用声明为插槽的方法。
//from Class A
void B::setValue(int newValue);
{
cout << newValue << endl;
}

在这里,您可以看到有关信号和插槽的更多信息。

https://doc.qt.io/qt-5/signalsandslots.html

如果要将信号从主窗口发送到串行通信,则应在主窗口和串行通信中的插槽中定义信号。在主窗口中,应该为此信号调用"emit"(可能来自on_connectButton_clicked)。 将信号连接到插槽最好从主窗口完成。SerailCom对象应该在那里知道,但是这样做。它将是这样的(伪代码):

connect(this, signal(sig_name), comm_object, slot(slot_name))