我搜索过这个问题,但他们和我的有点不同。我的问题是我不想从另一个线程接收信号,但我想发送一个。接收在我的应用程序中工作,但在尝试发送时,我收到错误,我试图发送到另一个线程...我不知道如何解决这个问题。 这是我的情况: 我有一个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);
这是代码: MainWindow.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
MainWindow.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();
}
答案 0 :(得分:-1)
QThread(connectionThread)实例存在于实例化它的线程(主线程)中,而不是在调用run()的线程中,因此如果要调用插槽,则需要使用文档中提供的第一种方法{{ 3}},查看工人 - 对象方法。