发出来自另一个类的信号
Emit a signal from another class
我有这段代码,由 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
固有,在它们之间发送消息,如事件。
- 将发出事件的类必须实现一个
signal
。
//Definition into the Class A (who emits)
signals:
void valueChanged(int newValue);
- 将接收事件(信号)的类必须实现一个公共
slot
,该必须具有与signal
相同的参数。
//Definition into the Class B (who receives)
public slots:
void setValue(int newValue);
- 将接收事件(信号)的类必须连接信号与插槽。使用
connect
方法链接来自类 A 类和实例的信号,以及来自类 B 实例的插槽。
//There is an instance of class A called aEmit.
void B::linkSignals()
{
connect(&aEmit, SIGNAL(valueChanged(int)), this, SLOT(setValue(int)));
}
- 要触发信号,请使用关键字
emit
将信号作为函数及其参数:。
//from Class A
void A::triggerSignal()
{
int myValue{23};
emit valueChanged(myValue);
}
- 在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))
相关文章:
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- Qt将信号与另一个类方法连接
- 从另一个线程发出信号是否安全?
- 在另一个线程上发出 QObject 信号的正确方法?
- glib:在另一个线程上处理自定义 GMainContext* 循环,不引发信号处理程序
- 连接类实例和另一个类实例中的对话框之间的槽和信号
- 如何让一个线程继续,而另一个线程正在等待C++中的信号量
- 发出来自另一个类的信号
- 更改如何从另一个窗口从Mainwindow接收信号
- 如果不同的线程调用另一个不同线程的相同信号,则需要静音
- 如何从另一个类发出信号
- 如何通过在另一个线程中提出的升压信号更新QT GUI
- 有没有一种方法可以将升压信号直接连接到另一个信号
- qt链接器错误,从另一个线程发出信号
- 如何从另一个线程的 cpp 代码同步调用 qml 信号处理程序
- 如何使用信号和插槽从qt表单中获取id,然后在链表中搜索它并使用另一个表单显示结果
- 使用Qt信号和插槽更改另一个类的标签文本
- Qt:使用信号和插槽从另一个类调用MainWindow::Ui
- C++/Qt-从一个线程到另一个线程槽的信号
- 级联导航窗格:连接到另一个qml文件的对象信号