WebEngine コンテンツ操作の例

Web コンテンツを読み込んで操作する方法を示します。

コンテンツ操作ではQt WebEngine ウィジェットを使用して JQuery を使用し、特殊効果とコンテンツ操作を備えたウェブブラウザを作成する方法を示します。

アプリケーションでは、QWebEnginePage::runJavaScript ()を呼び出して jQuery JavaScript コードを実行します。ブラウザ自体を構築するために、QWebEngineView を中心ウィジェットとしてQMainWindow を実装します。

例の実行

からサンプルを実行するには Qt Creatorからサンプルを実行するには、Welcome モードを開き、Examples からサンプルを選択します。詳細については、例の構築と実行を参照してください。

MainWindow クラスの定義

MainWindow クラスはQMainWindow を継承しています。このクラスは、アプリケーションとウェブ・コンテンツの両方に対してアクションを実行するための多くのスロットを実装しています:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(const QUrl& url);

protected slots:

    void adjustLocation();
    void changeLocation();
    void adjustTitle();
    void setProgress(int p);
    void finishLoading(bool);

    void viewSource();

    void highlightAllLinks();
    void rotateImages(bool invert);
    void removeGifImages();
    void removeInlineFrames();
    void removeObjectElements();
    void removeEmbeddedElements();

private:
    QString jQuery;
    QWebEngineView *view;
    QLineEdit *locationEdit;
    QAction *rotateAction;
    int progress;
};

また、jQueryを含むQString 、ウェブ・コンテンツを表示するQWebEngineView 、アドレス・バーとして動作するQLineEdit

MainWindowクラスの実装

コンストラクタの実装から始めます。コンストラクタの最初の部分では、progress の値を 0 に設定します。この値は、後のコードで Web ページの読み込みを視覚化するために使用します:

MainWindow::MainWindow(const QUrl& url)
{
    setAttribute(Qt::WA_DeleteOnClose, true);
    progress = 0;

次に、QFile 、ファイルの内容を読み込むことで、jQueryライブラリがロードされます。jQueryライブラリは、HTMLを操作するためのさまざまな関数を提供するJavaScriptライブラリです:

    QFile file;
    file.setFileName(":/jquery.min.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    jQuery.append("\nvar qt = { 'jQuery': jQuery.noConflict(true) };");
    file.close();

コンストラクタの後半では、QWebEngineView を作成し、スロットをビューのシグナルに接続します:

    view = new QWebEngineView(this);
    view->load(url);
    connect(view, &QWebEngineView::loadFinished, this, &MainWindow::adjustLocation);
    connect(view, &QWebEngineView::titleChanged, this, &MainWindow::adjustTitle);
    connect(view, &QWebEngineView::loadProgress, this, &MainWindow::setProgress);
    connect(view, &QWebEngineView::loadFinished, this, &MainWindow::finishLoading);

さらに、ブラウザのアドレス・バーとしてQLineEdit 。さらに、ブラウザのアドレス・バーとしてQSizePolicy を作成し、ブラウザの利用可能な領域を常に埋めるように を設定します。QWebEngineView::pageAction()からナビゲーション・アクションのセットとともに、QToolBarQLineEdit を追加します:

    locationEdit = new QLineEdit(this);
    locationEdit->setSizePolicy(QSizePolicy::Expanding, locationEdit->sizePolicy().verticalPolicy());
    connect(locationEdit, &QLineEdit::returnPressed, this, &MainWindow::changeLocation);

    QToolBar *toolBar = addToolBar(tr("Navigation"));
    toolBar->addAction(view->pageAction(QWebEnginePage::Back));
    toolBar->addAction(view->pageAction(QWebEnginePage::Forward));
    toolBar->addAction(view->pageAction(QWebEnginePage::Reload));
    toolBar->addAction(view->pageAction(QWebEnginePage::Stop));
    toolBar->addWidget(locationEdit);

コンストラクタの3番目の部分は、2つのQMenu ウィジェットを実装し、アクションのセットを割り当てています:

    QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
    QAction *viewSourceAction = new QAction(tr("Page Source"), this);
    connect(viewSourceAction, &QAction::triggered, this, &MainWindow::viewSource);
    viewMenu->addAction(viewSourceAction);

    QMenu *effectMenu = menuBar()->addMenu(tr("&Effect"));
    effectMenu->addAction(tr("Highlight all links"), this, &MainWindow::highlightAllLinks);

    rotateAction = new QAction(this);
    rotateAction->setIcon(style()->standardIcon(QStyle::SP_FileDialogDetailedView));
    rotateAction->setCheckable(true);
    rotateAction->setText(tr("Turn images upside down"));
    connect(rotateAction, &QAction::toggled, this, &MainWindow::rotateImages);
    effectMenu->addAction(rotateAction);

    QMenu *toolsMenu = menuBar()->addMenu(tr("&Tools"));
    toolsMenu->addAction(tr("Remove GIF images"), this, &MainWindow::removeGifImages);
    toolsMenu->addAction(tr("Remove all inline frames"), this, &MainWindow::removeInlineFrames);
    toolsMenu->addAction(tr("Remove all object elements"), this, &MainWindow::removeObjectElements);
    toolsMenu->addAction(tr("Remove all embedded elements"), this, &MainWindow::removeEmbeddedElements);

最後の行は、QWebEngineViewQMainWindow の中心ウィジェットとして設定します:

    setCentralWidget(view);
}

ページがロードされると、QWebEngineViewloadFinished() シグナルによってadjustLocation() がトリガーされ、アドレス・バーが更新されます:

void MainWindow::adjustLocation()
{
    locationEdit->setText(view->url().toString());
}

changeLocation() では、QUrl オブジェクトを作成し、QWebEngineView にページをロードするために使用します。新しいウェブページのロードが終了すると、adjustLocation() がもう一度実行され、アドレスバーが更新されます:

void MainWindow::changeLocation()
{
    QUrl url = QUrl::fromUserInput(locationEdit->text());
    view->load(url);
    view->setFocus();
}

adjustTitle() メソッドはウィンドウのタイトルを設定し、ロードの進捗状況を表示します:

void MainWindow::adjustTitle()
{
    if (progress <= 0 || progress >= 100)
        setWindowTitle(view->title());
    else
        setWindowTitle(QStringLiteral("%1 (%2%)").arg(view->title()).arg(progress));
}

void MainWindow::setProgress(int p)
{
    progress = p;
    adjustTitle();
}

このスロットはQWebEngineViewtitleChanged() シグナルによってトリガーされます。

ウェブページがロードされると、QWebEngineViewloadFinished() シグナルによってfinishLoading() メソッドがトリガーされます。このメソッドは、タイトルバーの進行状況を更新し、runJavaScript() を呼び出して、現在のウェブページに対して jQuery ライブラリを評価します:

void MainWindow::finishLoading(bool)
{
    progress = 100;
    adjustTitle();
    view->page()->runJavaScript(jQuery);

    rotateImages(rotateAction->isChecked());
}

つまり、JavaScriptはQWebEngineView にロードされたコンテンツの一部として見ることができるため、新しいページがロードされるたびにロードする必要があります。jQueryライブラリがロードされると、ブラウザでさまざまなjQuery関数を実行し始めることができます。

その後、rotateImages() 関数が明示的に呼び出され、新しく読み込まれたページの画像が toggle アクションの状態を尊重することを確認します。

最初のjQueryベースの関数、highlightAllLinks() は、現在のウェブページ内のすべてのリンクをハイライトするように設計されています。JavaScriptのコードは、ハイパーリンクのタグであるaという名前のウェブ要素を探します。そのような要素ごとに、CSSを使って背景色を黄色に設定します:

void MainWindow::highlightAllLinks()
{
    QString code = QStringLiteral("qt.jQuery('a').each( function () { qt.jQuery(this).css('background-color', 'yellow') } )");
    view->page()->runJavaScript(code);
}

rotateImages() 関数は、現在のウェブページ上の画像を回転させます。このJavaScriptコードは、CSS transformsに依存しています。すべてのimg要素を検索し、画像を180度回転させ、また元に戻します:

void MainWindow::rotateImages(bool invert)
{
    QString code;

    if (invert)
        code = QStringLiteral("qt.jQuery('img').each( function () { qt.jQuery(this).css('transition', 'transform 2s'); qt.jQuery(this).css('transform', 'rotate(180deg)') } )");
    else
        code = QStringLiteral("qt.jQuery('img').each( function () { qt.jQuery(this).css('transition', 'transform 2s'); qt.jQuery(this).css('transform', 'rotate(0deg)') } )");
    view->page()->runJavaScript(code);
}

残りのメソッドは、現在のウェブページからさまざまな要素を削除します。removeGifImages() は、ウェブページ上のすべての要素のsrc属性を検索して、ページ上のすべての GIF 画像を削除します。gifファイルをソースとするすべての要素が削除されます:

void MainWindow::removeGifImages()
{
    QString code = QStringLiteral("qt.jQuery('[src*=gif]').remove()");
    view->page()->runJavaScript(code);
}

removeInlineFrames() メソッドは、すべてのiframe要素またはインライン要素を削除します:

void MainWindow::removeInlineFrames()
{
    QString code = QStringLiteral("qt.jQuery('iframe').remove()");
    view->page()->runJavaScript(code);
}

removeObjectElements() メソッドは、すべてのobject要素を削除します:

void MainWindow::removeObjectElements()
{
    QString code = QStringLiteral("qt.jQuery('object').remove()");
    view->page()->runJavaScript(code);
}

removeEmbeddedElements() メソッドは、ページに埋め込まれたプラグインなど、embedタグを使用している要素をすべて削除します:

void MainWindow::removeEmbeddedElements()
{
    QString code = QStringLiteral("qt.jQuery('embed').remove()");
    view->page()->runJavaScript(code);
}

プロジェクトの例 @ code.qt.io

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.