问题
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