4

我有两个得到 QNetworkRequest。

我想处理来自不同方法的完成信号。

例如这是代码

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

    GetUserData();
    connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(GetUserDataCompleted(QNetworkReply*)));

    GetMessages();
    connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(GetMessagesCompleted(QNetworkReply*)));
}

这是我的一种方法

我试过 replay->deleteLater(); 但同样的结果

请给我一些有用的建议

void MainWindow::GetUserDataCompleted(QNetworkReply *replay)
{
    if(replay->error() == QNetworkReply::NoError)
    {
        QString getData = replay->readAll();
        QMessageBox msg;

        if(getData == "1")
        {
            msg.setText("User Is not Exits");
        }
        else
        {
            QDomDocument doc;

            if(doc.setContent(getData))
            {
                QDomElement domElem = doc.documentElement();

                QDomNode n = domElem.firstChild();
                while(!n.isNull()) {
                    QDomElement e = n.toElement(); // try to convert the node to an element.
                    if(!e.isNull()) {
                        msg.setText(e.namedItem("Image").childNodes().at(0).nodeValue());
                        msg.exec();
                    }
                    n = n.nextSibling();
                }
            }

            replay->deleteLater();
        }
    }
}
4

2 回答 2

6

您可以创建一个RequestSender负责处理请求的类。

每个RequestSender对象将处理一个唯一的请求。在创建QNetworkRequest将要发送的内容时,将使用该属性RequestSender“标记”它自己的请求。originatingObject此属性指示哪个对象发送了请求。当一个RequestSender对象收到回复时,它会通过originatingObject属性查看它是否是请求的发送者。有关更多信息originatingObject,您可以参考此处的文档:http: //qt-project.org/doc/qt-4.8/qnetworkrequest.html#originatingObject

以下是您可以执行的操作的示例。

请求者.hpp:

class RequestSender {
    public:
        RequestSender();
        ~RequestSender();
        void createRequest(/* Request parameters */);

    public slots:
        void endRequest(QNetworkReply* replay);
};

请求者.cpp:

RequestSender::RequestSender() {
    connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(endRequest(QNetworkReply*)));
}

RequestSender::~RequestSender() {
    disconnect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(endRequest(QNetworkReply*)));
}

void RequestSender::createRequest(/* Request parameters */) {
    QNetworkRequest * myRequest = 0;

    // Build myRequest with the request parameters

    myRequest->setOriginatingObject(this);
    nam->get(*myRequest);

}

void RequestSender::endRequest(QNetworkReply* replay) {
    if (replay->request().originatingObject() != this) {
        // That's not the request sent by the object -> stop the method here !
        return;
    }

    // Treatments on replay
}
于 2012-08-23T02:51:58.560 回答
2

您对 QNetworkAccessManager 执行的每个操作都将返回一个 QNetworkReply。这也有一个信号finished()。也许您可以将此信号连接到您的不同插槽。

于 2012-08-23T17:28:49.253 回答