views:

48

answers:

1

Please help me. I am struck-up with thread concept. Actually my problem : I want to display the cities List in the combobox. I am getting cities list from the webservice. I am using thread for update the combo box value after webserice call finished.

Here I can call the webservice. But I couldn't get the Reply.

I am using the following code.

MainWindow.cpp:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    CGNetwork *cgNetwork = new CGNetwork();
    ui->setupUi(this);

    renderThread = new RenderThread(cgNetwork);
    renderThread->start();

    connect(renderThread,SIGNAL(finished()),this,SLOT(initControls()));
}

void MainWindow::initControls()
{
    CGMainWindowUtility *pointer = CGMainWindowUtility::instance();
    QStringList cityitems;
    cityitems <<tr("All");
    cityitems.append(pointer->getCityList());
    QStringListModel *cityModel = new QStringListModel(cityitems, this);
    ui->cityComboBox->setModel(cityModel);
}

RenderThread.cpp:

RenderThread::RenderThread(CGNetwork *cgnetwork)
{
    cityUrl = "http://112.138.3.181/City/Cities";
    categoryUrl = "http://112.138.3.181/City/Categories";    
}

void RenderThread::run()
{
    qDebug()<< "THREAD Started";
    CGNetwork *cgnetworks = new CGNetwork();
    cgnetworks->getCityList(cityUrl);
}

CGNetwork.cpp:

void CGNetwork ::getCityList(const QUrl url)
{
    cityGuideNetworkAccessManager = new QNetworkAccessManager(this);
    qDebug()<<"connection";

    connect(cityGuideNetworkAccessManager, SIGNAL(finished(QNetworkReply*)),
        this, SLOT(parseCityList()));

    const QNetworkRequest cityRequest(url);
    cityReply= cityGuideNetworkAccessManager->get(cityRequest);

    connect(cityReply, SIGNAL(error(QNetworkReply::NetworkError)),
        this, SLOT(slotError()));
}

void  CGNetwork::parseCityList()
{
    qDebug()<<"Parsing";
    cgParser = new CGJsonParser();
    cgParser->CityRead(cityReply);
}
+2  A: 

Since QNetworkAccessManager works asynchronously, there's no need for a separate thread. You can call getCityList directly from your main thread and it won't block.

I think your slots weren't called because your QThread::run returned before any of the work its been doing had a chance to complete, since getCityList just initiated an http request without waiting for it (because QNetworkAccessManager::get doesn't block like I said above).

Also as a side note, your slots aren't getting the same parameters as their corresponding signals, I don't remember if Qt supports this.

Idan K
then,How could I solve this ? I am new to this.
Girija
don't use a separate thread
Idan K
Thanks Idan.. Got it.. Works fine....
Girija