Qt“没有匹配的调用连接函数",修改Qt Fortune Threaded Server示例 [英] Qt "no matching function for call to connect", modifying Qt Fortune Threaded Server example

查看:110
本文介绍了Qt“没有匹配的调用连接函数",修改Qt Fortune Threaded Server示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修改 Qt Fortune Threaded Server 示例以从连接中读取文本,然后将其回显.我在我的 FortuneThread.h 文件中定义了 tcpSocket 如下:

I am trying to modify the Qt Fortune Threaded Server example to read text from the connection and then echo it back. I defined tcpSocket in my FortuneThread.h file as follows:

QTcpSocket tcpSocket;

我新的线程运行函数如下所示:

My new run function for the thread looks as follows:

void FortuneThread::run()
{
    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }
    connect(&tcpSocket, SIGNAL(readyREAD()), this, SLOT(readCommand()) );
}

编译并运行,但是一旦我连接我就会收到这个错误(指连接线):

Which compiles and runs, but once I connect I get this error (referring to the connect line):

QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTcpSocket(0x1eeb920), parent's thread is QThread(0x1bb3f90), current thread is FortuneThread(0x1eeb8f0)
QObject::connect: No such signal QTcpSocket::readyREAD() in ../fortune/fortunethread.cpp:60

有人可以向我解释原因吗?由于 tcpSocket 是在 FortuneThread 类(作为单独的线程运行)中定义的,并且this"指的是 FortuneThread,我假设两个对象都在线程内?如何解决这个问题?

Can someone explain the cause to me? Since tcpSocket is defined inside the FortuneThread class (which is run as a separate thread), and "this" refers to FortuneThread, I assume both objects are inside the thread? How to fix this?

推荐答案

您的套接字对象已在主线程中创建,但您正在从不同的线程访问它.您需要在线程的 run() 方法内创建它.定义套接字的位置无关紧要.当 C++ 运行时库进行静态对象初始化时,它将从主线程创建.

Your socket object has been created in the main thread, but you're accessing it from a different thread. You need to create it inside of the thread's run() method. The location where the socket is defined doesn't matter. It will be created from the main thread when the C++ runtime library is doing static object initialization.

QTcpSocket * tcpSocket;

...

void FortuneThread::run() {
  tcpSocket = new QTcpSocket;
  ...
}

这篇关于Qt“没有匹配的调用连接函数",修改Qt Fortune Threaded Server示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆