文章目錄
一、環境準備
二、代碼實現
三、測試
一、環境準備
首先,確保你的Qt安裝包含了QtWebEngine模塊。我的Qt是5.12.9并且使用MSVC來編譯項目。在項目文件中需要添加以下配置,其中在Qt中配置MSVC,建議去看看這位大佬的博客:Qt 添加MSVC2017編譯器(2022年保姆級教程,不安裝完整VS)_qt msvc2017-CSDN博客
確保:
QT += core gui webenginewidgets
二、代碼實現
mainwindow.cpp,主要實現的簡單網頁瀏覽器,其通過QWebEngineView組件實現了網頁內嵌功能。如下為測試demo文件代碼:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWebEngineView>
#include <QWebEnginePage>
#include <QWebEngineProfile>
#include <QStyle>
#include <QApplication>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);// 設置窗口標題和大小setWindowTitle("Web Browser");resize(1024, 768);// 創建工具欄toolBar = new QToolBar(this);addToolBar(toolBar);// 創建地址欄urlLineEdit = new QLineEdit(this);urlLineEdit->setPlaceholderText("Enter URL (e.g., https://www.google.com)");urlLineEdit->setStyleSheet("QLineEdit { padding: 5px; border-radius: 3px; }");toolBar->addWidget(urlLineEdit);// 創建前進按鈕goButton = new QPushButton("Go", this);goButton->setStyleSheet("QPushButton { padding: 5px 15px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; }""QPushButton:hover { background-color: #45a049; }");toolBar->addWidget(goButton);// 創建網頁視圖webView = new QWebEngineView(this);setCentralWidget(webView);// 創建進度條progressBar = new QProgressBar(this);progressBar->setMaximumHeight(2);progressBar->setTextVisible(false);progressBar->setStyleSheet("QProgressBar { border: none; background-color: #f0f0f0; }""QProgressBar::chunk { background-color: #4CAF50; }");statusBar()->addPermanentWidget(progressBar);// 連接信號和槽connect(goButton, &QPushButton::clicked, this, &MainWindow::loadPage);connect(urlLineEdit, &QLineEdit::returnPressed, this, &MainWindow::loadPage);connect(webView, &QWebEngineView::urlChanged, this, &MainWindow::updateUrl);connect(webView, &QWebEngineView::loadProgress, this, &MainWindow::updateProgress);connect(webView, &QWebEngineView::titleChanged, this, &MainWindow::updateTitle);// 設置初始頁面webView->setUrl(QUrl("https://www.google.com"));
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::loadPage()
{QString url = urlLineEdit->text();if (!url.startsWith("http://") && !url.startsWith("https://")) {url = "https://" + url;}webView->setUrl(QUrl(url));
}void MainWindow::updateUrl(const QUrl &url)
{urlLineEdit->setText(url.toString());
}void MainWindow::updateProgress(int progress)
{progressBar->setValue(progress);if (progress == 100) {progressBar->hide();} else {progressBar->show();}
}void MainWindow::updateTitle(const QString &title)
{setWindowTitle(title + " - Web Browser");
}
三、測試
1.打開博客網頁:
2.打開B站網頁:?
?
?合理!!!!!