[QT]槽函数中获得发送信号的对象 用来在槽函数中delete避免内存泄露 以及多线程中线程无法释放

QObject* send = dynamic_cast<QObject*>(sender());

适合用于所有继承QObject 的类

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt,子线程向主线程传递参数可以使用以下方式: 1. 使用信号机制:在子线程定义一个信号,主线程定义一个函数,子线程通过emit发送信号并传递参数。 2. 使用QMetaObject::invokeMethod():在子线程通过该方法调用主线程函数,并传递参数。 下面是使用信号机制的示例代码: ```cpp // MyThread.h #include <QThread> class MyThread : public QThread { Q_OBJECT public: explicit MyThread(QObject *parent = nullptr); signals: void sendData(QString data); protected: void run() override; }; // MyThread.cpp #include "MyThread.h" #include <QDebug> MyThread::MyThread(QObject *parent) : QThread(parent) { } void MyThread::run() { // 执行子线程任务 QString data = "Hello, World!"; // 子线程要传递的数据 emit sendData(data); // 发送信号并传递数据 } // MainWindow.h #include <QMainWindow> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_recvData(QString data); private: Ui::MainWindow *ui; }; // MainWindow.cpp #include "MainWindow.h" #include "ui_MainWindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_recvData(QString data) { qDebug() << "Received data from sub-thread: " << data; } void MainWindow::on_pushButton_clicked() { MyThread *thread = new MyThread(this); connect(thread, &MyThread::sendData, this, &MainWindow::on_recvData); // 连接信号函数 thread->start(); // 启动子线程 } ``` 在上面的代码,子线程通过emit发送sendData信号,并将数据作为参数传递进来,主线程通过connect连接了MyThread的sendData信号和MainWindow的on_recvData函数,当MyThread发送sendData信号时,主线程会自动调用on_recvData函数,并将数据作为参数传递进来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值