PDA

View Full Version : unable to update label from another thread



dhanya.v
4th October 2012, 09:39
Iam new to Qt programming.Qt 4.7.3 is using for the development.
We are developing a program to read from the multiple file(initially started with two) and display in to the Gui.File reading is doing from one thread and the read value is passing to the label in Gui thread.
Here the code.
fileread.cpp


#include "fileread.h"
#include "ui_fileread.h"
#include "filethread.h"
#include<QThread>
#include <QtGui>
#include<QLabel>
fileread::fileread(QWidget *parent) :
QWidget(parent),
ui(new Ui::fileread)
{
ui->setupUi(this);

}

fileread::~fileread()
{
delete ui;
}


void fileread::on_pushButton_clicked()
{

QString fname1="E:/QT/test1.txt";
QString fname2="E:/QT/test3.txt";


filethread fthread1(fname1),fthread2(fname2);

QObject::connect(&fthread1, SIGNAL(setlabel(QString)),ui->label_2, SLOT(setText(QString)), Qt::QueuedConnection);
QObject::connect(&fthread2, SIGNAL(setlabel(QString)),ui->label_3 , SLOT(setText(QString)), Qt::QueuedConnection);

fthread1.start();
fthread2.start();

fthread1.wait();
fthread2.wait();

}


filethread.cpp

filethread::filethread(QString text) : QThread()
{

fname=text;
}


QMutex mutex;
void filethread::run()
{
QFile fp(fname);
if(fp.open(QIODevice::ReadOnly))
{
QDataStream in(&fp);
}
QTextStream in(&fp);

QString line = in.readLine();

while (!line.isNull())
{

mutex.lock();
emit setlabel(line);
sleep(1);
qDebug()<<"Content from the file:"<<line;
line = in.readLine();
mutex.unlock();

}
}

Here what problem Iam facing is only last line from the file is displaying in the label.Other text from the file is not comming in the label.All line from the file should come in the label.File is reading properly,that I understood from qDebug function.I think Gui thread is get blocked because of that it is not comming for all line from file.
Iam in this problem for about three weeks...
Please help me..

Santosh Reddy
4th October 2012, 12:05
You are emiting setlabel() signal for every line, and it is connected to setText() which will replace the complete label text (in your case the previous line will be erased). One solution would be implement a custom slot where in you read the current text and append with new line and then setText() on the label. One other option you can use QPlainTextEdit (instead of QLabel) and connect to appendPlainText() slot