我想从另一个类QString
转换toInt
,但它接缝失败,因为结果为0,而它应该是5,其余代码可以正常工作。
因为我是C / Qt的新手并且发现课程有点令人困惑,我认为我的班级做错了。
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
答案 0 :(得分:4)
您正在访问新初始化的实例m_replyStr
的{{1}},该实例未在其tmp
中设置任何内容。所以它的默认初始值为“空字符串。”
修改强>
根据您的后续问题,也许您正在寻找类似的内容?
m_replyStr