PDA

View Full Version : Emitting signals in other thread



mvbhavsar
27th May 2011, 19:24
Hi,

I have a requirement where I have to call QNetworkAccessManager methods from a class which has base class as QThread. And I also I have to capture QNetworkAccessManager's finished() signal.


class test: public QThread{
Q_OBJECT
public:
test(QObject *parent=0);

private:
QNetworkAccessManager *manager
}

when it emits signal by run() method in a class, it fails because it complains about conflict between parent thread and child thread.
Need a solution to handle this


Thanks

Manish

wysota
27th May 2011, 20:14
Please show us some implementation code.

DanH
27th May 2011, 22:08
You can signal between threads, if you read and follow the signals and slots (http://doc.qt.nokia.com/4.7/signalsandslots.html) docs carefully. But you need to understand that you can't, in a general sense, pass Qt objects (derived from QObject) between threads since they're "owned" by the thread where they're created.

wysota
27th May 2011, 22:52
The problem is probably totally different. I'm expecting that the QNAM object is created in the constructor instead of the run() method.

mvbhavsar
7th June 2011, 14:11
Please find attached code. Signal is not getting emitted in this and slot is not called.

wysota
7th June 2011, 14:40
You are trying to access a QObject (QNetworkReply) from a different thread (main thread, as this is where your thread object lives) than the thread it belongs to (the thread represented by your thread object where QNetworkAccessManager lives).

mvbhavsar
7th June 2011, 20:35
Ok, But what is way out for this. Hunted lot for solution but no luck.
Please provide the solution to handle this situation

DanH
7th June 2011, 22:12
connect() has an optional parameter. Perhaps you should use it. But keep in mind that the receiving thread must be running an "event loop" or nothing will happen.

Santosh Reddy
8th June 2011, 08:40
I think you have things in place, only miss these


void mythread::run()
{
QNetworkAccessManager *manager= new QNetworkAccessManager();
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(showData(QNetworkReply*)));
QNetworkReply *rep = manager->get(QNetworkRequest(QUrl("http://www.google.co.in")));
exec(); //Add this
}

threadcross::~threadcross()
{
th.exit(0); //Add this, to make sure you stop and exit the thread
while(th.isRunning()); //wait for the thread to exit, and then continue, actual thread will may take longer to finish and exit, hence this wait is required to avoid application crashing while closing. There are better ways to do this, you can figure them out eventually
delete ui;
}

wysota
8th June 2011, 09:17
Ok, But what is way out for this. Hunted lot for solution but no luck.
Please provide the solution to handle this situation

http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/