我有 mainwindow
类,里面有这样的插槽:
void MainWindow::connect_to_server(const std::string& nickname,
const std::string& ip,
int port)
{
remote_server = new Server(nickname, ip, port);
connect(remote_server, SIGNAL(error()), SLOT(connection_failed()));
auto thread = new QThread(this);
remote_server->moveToThread(thread);
connect(thread, SIGNAL(started()), remote_server, SLOT(establish_connection()));
connect(remote_server, SIGNAL(stop_thread()), thread, SLOT(quit()));
thread->start();
}
void MainWindow::action_disconnect_triggered() {
if (remote_server == nullptr) {
return;
}
remote_server->disconnect();
remote_server = nullptr;
}
和Server
类:
void Server::establish_connection() {
master_socket = std::move(
std::unique_ptr<QTcpSocket>(new QTcpSocket(nullptr))
);
master_socket->connectToHost(ip.c_str(), port);
master_socket->waitForConnected(timeout*1000);
if (master_socket->state() == QAbstractSocket::UnconnectedState) {
disconnect();
emit error();
}
emit stop_thread();
}
void Server::disconnect() {
if (master_socket) {
master_socket->disconnectFromHost();
}
}
最初,我调用 MainWindow::connect_to_server
客户端成功连接到远程服务器。然后,我调用 MainWindow::action_disconnect_triggered
并在这个阶段出现这样的错误:
顺便说一句,当我在 OS X 10.11 中运行它时,不会出现错误并且一切正常。我做错了什么,我该如何解决?
最佳答案
remote_server->disconnect();
可能是这里的问题。
您不直接发送事件,而是调用该函数,它会在您的主线程中被调用。
试试 QMetaObject::invokeMethod(remote_server, "disconnect", Qt::QueuedConnection);
看看这个问题是否仍然存在
干杯
关于c++ - Qt 无法将事件发送到不同线程拥有的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34039637/