user2880783
user2880783

Reputation: 165

Set widget label text in a thread in Qt

I'm new in Qt and I'm really stuck with threading. I know that this is question answered many times, but I can't figure out how to solve my problem. I have widget application with several labels and I have a class that reads data from serial port. I need to read data continuously and show them in labels. I've found many different answers about threading in Qt, but I cant get any of them to work. Can anyone point me to the right direction.

This code shows approximately what I want to achieve:

serial port class:

SerialPort *port;

int value1; 
int value2;
int value3;

void Port::ReadData()
{
   // First I send data to serial port as a QByteArray

   QByteArray data = port.readAll();

   value1 = data[0];
   value2 = data[1];
   value3 = data[3];

   // Of course it's not really like this but I process data and assign them to    
      variables       
}

Variables value1, value2 and value3 are public and I use label1->setText(portClass.value1) to show data. When I use this with a button click ti works but I want to close it to a loop and read data continuously.

Upvotes: 2

Views: 1022

Answers (1)

ratchet freak
ratchet freak

Reputation: 48186

labels have slots you can call from any thread using invokeMethod:

QMetaObject::invokeMethod (label1, "setText",
                           Q_ARG(QString,data[0]);
QMetaObject::invokeMethod (label2, "setText",
                           Q_ARG(QString,data[1]);
QMetaObject::invokeMethod (label3, "setText",
                           Q_ARG(QString,data[2]);

Upvotes: 3

Related Questions