Вопрос

I have a QThread defined in MyThread.cpp and .h. There I have a private QTcpSocket.

class MyThread: public QThread {

    Q_OBJECT

public:
    MyThread();
    virtual ~MyThread();

public slots:
    void reconnect();
signals:

protected:
    void run(void);

private:
    QTcpSocket *socket;
};

void MyThread::run(void) {
    bool connected = false;

    connected = prepareSocket(QString::fromLatin1((Global::directionIPSerialServer).toLocal8Bit().data()), 8008, socket);
}

On the other hand, I have a set of functions defined in Functions.cpp and .h, which are not defined into a Functions class, but a namespace.

bool Functions::prepareSocket(QString address, int port, QTcpSocket *socket) {
    socket->connectToHost(address, port);
    if(!socket->waitForConnected(Global::maxTimueToConnectByTCP)){
        qDebug()<<"Error: "<<socket->errorString();
        return false;
    }
    return true;
}

Then, correct me if I'm wrong, when I call a function into Functions to connect the MyThread's QTcpSocket to a host, I'm supposing I am on the same thread, since I'm calling the function from the thread I've created and not a different one.

Despite this, on socket->connectToHost I am getting QObject: Cannot create children for a parent that is in a different thread. twice.

Why is that? What's wrong?

Это было полезно?

Решение

Try: QObject::moveToThread. This should do the trick.

Другие советы

You should not derive from QThread. Implement everything on a class derived from QObject. You can then optionally call moveToThread() on that QObject to move it to a new thread. You'll find, though, that there's normally no need to move it to a new thread anyway, because now you'll have asynchronous, nonblocking code that won't stall your GUI thread.

They key to doing it is to never use waitxxx calls. Whenever you want to wait for something, you'll find that there's a signal that gets emitted when that thing happens (or fails). Connect a slot to that signal. You may need to do it multiple times -- different slots for different signals. That's how you correctly code asynchronous, event driven applications.

You only resort to using blocking calls when no other API exists. Database drivers and name resolvers are notoriously bad in this respect, but they are the lonely counterexamples. Let them die in solitude, I say.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top