Question

I want to convert a QString from another class toInt, but it seams to fail because the result is 0 while it should be 5 and the rest of the code works. Because I am new to C/Qt and find classes a bit confusing, I think I have done something wrong with my classes.

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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

void Widget::on_pushButton_clicked()
{
    MyClass tmp;
    int myNumber = tmp.m_replyStr.toInt();
    ui->lcdNumber->display(myNumber);
}

MyClass::MyClass()
{
    m_manager = new QNetworkAccessManager(this);

    connect( m_manager, SIGNAL(finished(QNetworkReply*)),
             this, SLOT(replyFinished(QNetworkReply*)));
}

void MyClass::fetch()
{
    m_manager->get(QNetworkRequest(QUrl("http://example.tld/test.html"))); // html contains only the number 5
}

void MyClass::replyFinished(QNetworkReply* pReply)
{
    QByteArray data=pReply->readAll();
    QString str(data);
    m_replyStr = str;
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QObject>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>

namespace Ui {
    class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
};

class MyClass : public QObject
{
    Q_OBJECT

public:
    MyClass();
    void fetch();
    QString m_replyStr;

public slots:
    void replyFinished(QNetworkReply*);

private:
    QNetworkAccessManager* m_manager;
};

#endif // WIDGET_H
Was it helpful?

Solution

You're accessing m_replyStr of a newly initialised instance tmp, which doesn't set anything into its m_replyStr. So it has the default-initialised value of "empty string."

EDIT

Based on your follow-up question, perhaps you were looking for something like this?

class MyClass;

class Widget : public QWidget
{
  Q_OBJECT

public:
  Widget(MyClass &myClassInstance, QWidget *parent = 0);
  ~Widget();

private slots:
  void on_pushButton_clicked();

private:
  Ui::Widget *ui;
  MyClass *myClass;
};

Widget::Widget(MyClass &myClassInstance, QWidget *parent = 0)
  : QWidget(parent)
  , ui(new Ui::Widget)
  , myClass(&myClassInstance)
{
  ui->setupUi(this);
}

void Widget::on_pushButton_clicked()
{
    int myNumber = myClass->m_replyStr.toInt();
    ui->lcdNumber->display(myNumber);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top