gpt4 book ai didi

c++ - 从另一个类发出信号

转载 作者:行者123 更新时间:2023-11-27 23:40:17 24 4
gpt4 key购买 nike

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

我有ma​​inwindow.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!";
}

这是 mainwindow.cpp 的 header:

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

private:
Ui::MainWindow *ui;

};

所以,我想从 mainwindow 类发送一个信号到 serialcomunication 类,在这里调用一个函数:

第二个*.cpp文件:Serialcommunication.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
}

和串行通信 header :

class SerialCommunication : public QObject
{
Q_OBJECT
private:

//some other fucntions

public:
explicit SerialCommunication(QObject *parent = nullptr);
~SerialCommunication();
};

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

最佳答案

首先,您需要了解QT的特性SlotsSignal的基本理论。它们允许 QOBJECT 固有的任何对象在它们之间发送消息,例如事件。

  1. 发出 事件的类必须实现信号
//Definition into the Class A (who emits)
signals:
void valueChanged(int newValue);
  1. 将接收事件 (signal) 的类必须实现一个公共(public) 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类中,调用声明为slot的方法。
//from Class A
void B::setValue(int newValue);
{
cout << newValue << endl;
}

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

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

关于c++ - 从另一个类发出信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55656239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com