Search code examples
c++qtqmlqnetworkrequest

How to define QNetworkRequest object from cpp to qml


I have made a frontend piece of registration page in QML and processing of textInput using the setContextProperty function. But I have a problem when I need to do post request. Responsible for this method

void NetworkManager::sendRequest(const QNetworkRequest &request, const QJsonObject &data) {
    QNetworkReply *reply = m_manager->post(request, QJsonDocument(data).toJson());
    m_replies.append(reply);
}

m_manager and m_replies defined in class so

private:
    QNetworkAccessManager *m_manager;
    QList<QNetworkReply *> m_replies;

I tried to use method sendRequest inside onClicked signal on reg button. But if I trying to define QNetworkRequest object in QML I have an error:
no matching function for call to 'QQmlContext::setContextProperty(const char[15], QNetworkRequest&)'

I have read the documentation of QQmlContext and QVariant, and I understood, that I can't to define QNetworkRequest object in this way. I tried to define a button from QML to C++ with objectName and use signals and slots but it isn't working to. Maybe someone knows any methods to define C++ objects in QML, or QML to C++? I haven't found it yet.


Solution

  • Well, I don't have any ideas, how to define a QNetworkRequest object from cpp to qml. Because of this I have made several identical methods, with hardcode URL inside and query items

    void NetworkManager::sendAuthRequest(QString authPhone){
        QUrl url("http://89.221.60.161:3000/api/auth/login");
    
        QUrlQuery query;
        QByteArray postData;
        query.addQueryItem("phone", authPhone);
        query.addQueryItem("notificationToken", "d3ef6dac-38b5-442e-898b-b030d014efb9");
    
        postData = query.toString(QUrl::FullyEncoded).toUtf8();
    
        QNetworkRequest request(url);
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    
        m_manager->post(request, postData);
    
    };

    the function parameters are passed from qml, where I have defined the parameters in advance

        onClicked:{
            var authPhone = inputNumber.text
            manager.sendAuthRequest(authPhone);
        }

    I don't like this solution, but maybe it will help someone, or someone will come up with a better solution.