Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to run Qt UI and Udp port reception thread in parellel?



  • I am developing a ui using python and pyqt5. In my ui a QTableWidget and a QLineEdit is there .i need to continuously check a port(udp communication) whether any values received in the port.based on the received values in the port i need to update my QTableWidget and QLineEdit values continuesly.

    I created one thread to continuously monitor the reception port. While starting and running the mentioned thread, UI got stuck. Any solution for running the thread and UI in parallel?



  • @jishnuprasad
    Hi and welcome.

    A lot of people/beginners here launch out thinking they need to use threads, when in fact they don't. Threads in Qt are advanced usage, and when Python is involved it gets more complicated.

    Because of Qt's use of signals and slots (you should pause development now and read through it before you rethink your approach), and the asynchronous nature of UDP/TCP/socket calls, unless you have a special use-case you probably do not want any threads here.

    I created one thread to continuously monitor the reception port.

    You should not need to take that approach in Qt.

    Just create your GUI, and set up slots on the signals emitted from the QUdpSocket class. When a slot is called in response to some new data arriving, use that to update whatever desired in your UI, and then exit the slot. That should be all there is to it!

    Look at the very simple example in https://doc.qt.io/qt-5/qudpsocket.html#details. See how all it does is

        connect(udpSocket, &QUdpSocket::readyRead,
                this, &Server::readPendingDatagrams);
    
    void Server::readPendingDatagrams()
    {
        while (udpSocket->hasPendingDatagrams()) {
            QNetworkDatagram datagram = udpSocket->receiveDatagram();
            processTheDatagram(datagram);
        }
    }
    

    That is the pattern. Note that there is no "continuously monitor the reception port", instead Qt infrastructure will call readPendingDatagrams() whenever new datagrams arrive. Just put whatever you want to do with the received data into your implementation of processTheDatagram(datagram).

    [EDIT You can see the Python equivalent of this example in https://doc.qt.io/qtforpython/PySide2/QtNetwork/QUdpSocket.html#detailed-description. That's for PySide2, but you can adapt as necessary for PyQt5. One thing that looks odd to me is it uses

        self.connect(udpSocket, SIGNAL('readyRead()'),
                     self, SLOT('readPendingDatagrams()'))
    

    where I would have expected the more Python-natural

        udpSocket.readyRead.connect(self.readPendingDatagrams)
    

    ]


Log in to reply