QWebEnginePage :: toHtml返回空字符串

时间:2015-08-12 13:05:26

标签: qtwebengine qt5.5

我想在销毁类之前保存QWebEnginePage。在运行时,输出为:

Writing bookmarks...
Bookmarks empty!

QWebEnginePage :: toHtml否则返回页面的正确内容,无论它是否在QWebEngineView中设置。

bookmarkmanager.h

#ifndef BOOKMARKMANAGER_H
#define BOOKMARKMANAGER_H

#include <QWebEnginePage>

class BookmarkManager : public QObject
{
    Q_OBJECT
public:
    BookmarkManager(QObject *parent = 0);
    ~BookmarkManager();

    QWebEnginePage *page();

public slots:
    void saveBookmarks();

private:
    QWebEnginePage *m_page;
};

#endif // BOOKMARKMANAGER_H

bookmarkmanager.cpp

#include "bookmarkmanager.h"
#include <QFile>
#include <QDir>
#include <QStandardPaths>
#include <QSettings>

BookmarkManager::BookmarkManager(QObject *parent) : QObject(parent)
{
    // skipped code to create and load a QFile bookmarks_file
    m_page = new QWebEnginePage(this);
    m_page->setHtml(QString(bookmarks_file.readAll()), QUrl("about:bookmarks"));

    bookmarks_file.close();
}

BookmarkManager::~BookmarkManager()
{
    saveBookmarks();
}

QWebEnginePage *BookmarkManager::page()
{
    return m_page;
}

void BookmarkManager::saveBookmarks()
{
    qDebug("Writing bookmarks...");
    m_page->toHtml([](const QString &result){
        if(!result.isEmpty()) {
            qDebug(qUtf8Printable(result));

            QSettings settings;
            QFile bookmarks_file(settings.value("bookmarks/location",
                                                QDir::toNativeSeparators(QStandardPaths::standardLocations(QStandardPaths::DataLocation).at(0)) + "/bookmarks.html").toString());
            if(bookmarks_file.open(QIODevice::WriteOnly)) {
                bookmarks_file.write(result.toUtf8());
                bookmarks_file.flush();
                bookmarks_file.close();
                qDebug("Bookmarks written successfully");
            } else {
                qDebug("Could not write bookmarks: %s", qUtf8Printable(bookmarks_file.errorString()));
            }
        } else {
            qDebug("Bookmarks empty!");  // should not be reached!
        }
    });
}

0 个答案:

没有答案