Read local file from QWebView using Ajax request

孤者浪人 提交于 2019-12-23 17:51:35

问题


I am developing a Qt/C++ program which encapsulates an HTML5/JQuery web app.

I used to make Ajax requests to read files from a server. But now, I would like Qt to read a file from the local disk and send its content to my web app.

I think I need Qt to catch Ajax requests from the web app and return the file content as the Ajax request result.

The problem is I don't know how to do. For now, I've not found anything about that on google.

Any help is welcome!


回答1:


I finally found how to do it. I overrode QNetworkAccessManager.

MyQNetworkAccessManager .h:

class MyQNetworkAccessManager : public QNetworkAccessManager
{
    Q_OBJECT

protected:
    virtual QNetworkReply * createRequest(Operation op, const QNetworkRequest & req, QIODevice * outgoingData = 0);
};

MyQNetworkAccessManager.cpp:

QNetworkReply * MyQNetworkAccessManager::createRequest(Operation op, const QNetworkRequest & req, QIODevice * outgoingData) {
    QUrl url = req.url();
    QString path = url.path();

    if (op == QNetworkAccessManager::GetOperation && path.endsWith("xml")) {
        QUrl newUrl;

        if(path.endsWith("..")) {
            newUrl.setUrl("...");
        }
        else if(path.endsWith("...")) {
            newUrl.setUrl("...");
        }
        else {
            newUrl = url;
        }
        return QNetworkAccessManager::createRequest(QNetworkAccessManager::GetOperation, QNetworkRequest(newUrl));
    }
    else
    {
        return QNetworkAccessManager::createRequest(op, req, outgoingData);
    }
}

MainWindow.cpp:

// ....

QWebView *qWebView = new QWebView();

QWebPage *page = qWebView->page();
MyQNetworkAccessManager *networkManager = new MyQNetworkAccessManager();
page->setNetworkAccessManager(networkManager);

qWebView->setPage(page);

qWebView->load(QUrl("..."));

// ....


来源:https://stackoverflow.com/questions/14280531/read-local-file-from-qwebview-using-ajax-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!