我已经搜索过这个问题,但它们与我的有点不同。我的问题是我不想从另一个线程接收信号,但我想发送一个。接收在我的应用程序中工作,但是当尝试发送时,我收到错误,我试图发送到另一个线程......我不知道如何解决这个问题。
这是我的情况:
我有一个 GUI 应用程序。在 MainWindow 类中,我创建了一个从 Qthread 继承的 myThread 对象。
然后我开始新的线程。在 MainWindow 中存在信号,在 myThread 中存在槽(此代码在主窗口中运行)。当我尝试做:
connect(this, SIGNAL(disconnect(),
connectionThread, SLOT(stop()));
stop() 是连接线程中的一个插槽,并且 disconnect() 是来自 MainWindow 的信号。当信号发出时,我得到:
ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 128f8250. Receiver '' (of type 'QNativeSocketEngine') was created in thread 14bae218", file kernel\qcoreapplication.cpp, line 521
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.
有没有办法克服这个问题?我需要能够通过信号和槽向我创建的线程发送和接收事件。我真的会帮助所有帮助!
PS:我试过直接链接。
connect(this, SIGNAL(disconnectFromOven()),
connectionThread, SLOT(stop()), Qt::DirectConnection);
这是代码:
主窗口.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void moveUndoView();
signals:
void disconnectFromOven();
};
#endif // MAINWINDOW_H
主窗口.cpp:
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
initComponents();
QString ip = "10.10.10.17";
int port = 5432;
connectionThread = new TcpThread(ip, port, connectAndStay);
show();
// tcp connection
connect(connectionThread, SIGNAL(connectionEstablished()),
this, SLOT(on_connectionEstablished()));
connect(connectionThread, SIGNAL(connectionNotEstablished()),
this, SLOT(on_connectionNotEstablished()));
connect(this, SIGNAL(disconnectFromOven()),
connectionThread, SLOT(stop()));
}
void MainWindow::on_action_Disconnect_triggered()
{
emit disconnectFromOven();
}
tcpthread.h:
#ifndef TCPTHREAD_H
#define TCPTHREAD_H
#include <QThread>
#include <QDebug>
#include "tcpconnection.h"
class TcpThread : public QThread
{
Q_OBJECT
public:
explicit TcpThread(QString& address,
int& port, conType_t conType, QObject *parent = 0);
void run(); // inherited
signals:
void connectionStatusOk();
void connectionEstablished();
void connectionNotEstablished();
private slots:
void stop();
void connectionClosed();
void connectionOpened();
void connectionOpenFailed();
};
#endif // TCPTHREAD_H
tcpthread.cpp:
#include "tcpthread.h"
TcpThread::TcpThread(QString& address,
int& port, conType_t conType, QObject *parent) :
QThread(parent)
{
this->address = address;
this->port = port;
this->conTypeRequested = conType;
}
void TcpThread::stop()
{
qDebug() << "Thread stop called, requesting disconnect";
tcpCon->doDisconnect();
}
最佳答案
QThread (connectionThread) 实例存在于实例化它的线程(主线程)中,而不是在调用 run() 的线程中,因此如果要调用槽,则需要使用文档 here 中介绍的第一种方法,看看工作对象方法。
关于multithreading - Qt向不同线程发送信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29922030/