Discussion Board

Results 1 to 2 of 2
  1. #1
    Registered User
    Join Date
    Aug 2010

    Question QUdpSocket and QThread! (Please help)

    Hi there,

    i would like to be always connected with a udp server... but my gui should never block!

    Therefore i decided to move the udpsocket in a single thread... The thread reads data and parses the data and after that the thread emits signals... (signals not implemented yet!)

    Also the thread should sometimes write some data to the socket... (not implemented yet)

    My code works but i'm not sure if this code/design is correct.

    #include "uthread.h"
    #include <iostream>
    UThread::UThread(QObject* parent) : QThread(parent)
    void UThread::run() {
        socket = new QUdpSocket();
        socket->bind(QHostAddress::LocalHost, 2323);
        QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readData()), Qt::DirectConnection);
    void UThread::readData() {
        while(socket->hasPendingDatagrams()) {
            QByteArray datagram;
            QHostAddress sender;
            quint16 port;
            socket->readDatagram(datagram.data(), datagram.size(), &sender, &port);
    void UThread::parse(QByteArray data) {
        QString q(data);
        std::cout << q.toStdString() << std::endl;
    Previously there was a little problem: I only received one datagram and i got the warning "QObject: Cannot create children for a parent that is in a different thread. "

    I fixed it with this line (I added DirectConnection).
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readData()), Qt::DirectConnection);
    Is this the right way?

    Thank you!
    Last edited by gast23; 2010-08-11 at 09:47.

  2. #2
    Super Contributor
    Join Date
    Mar 2009

    Re: QUdpSocket and QThread! (Please help)

    The code looks okay to me; Anyway note that the QThread object and socket are actually in different threads... that's why you need connect those objects directly.

    Personally I prefer t move an Object to a thread. Take a look at
    that's another approach but your is valid.

Similar Threads

  1. QThread and MainWindow (Qt designer)
    By darksoul_e in forum Qt
    Replies: 11
    Last Post: 2010-05-18, 14:12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts