Qt Creater關於Qt WebEngine模組的介紹
阿新 • • 發佈:2019-01-31
從Qt5.5開始,Qt WebKit模組被廢棄,被Qt WebEngine模組取代
如果是windows,需要MSVC版本的QT,VS 2013
.pro檔案:
main.cpp檔案:#------------------------------------------------- # # Project created by QtCreator 2016-07-15T14:01:58 # #------------------------------------------------- QT += core gui QT += webenginewidgets greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = mywebengine TEMPLATE = app SOURCES += main.cpp\ mainwindow.cpp HEADERS += mainwindow.h FORMS += mainwindow.ui
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
MainWindow.cpp檔案:
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QWebEngineView> #include <QLineEdit> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); view = new QWebEngineView(this); view->load(QUrl("http://localhost/wangye/index.php")); setCentralWidget(view); resize(1024, 680); progress = 0; // 關聯訊號和槽 connect(view, &QWebEngineView::loadProgress, this, &MainWindow::setProgress); connect(view, &QWebEngineView::titleChanged, this, &MainWindow::adjustTitle); connect(view, &QWebEngineView::loadFinished, this, &MainWindow::finishLoading); locationEdit = new QLineEdit(this); locationEdit->setText("http://localhost/wangye/index.php"); connect(locationEdit, &QLineEdit::returnPressed, this, &MainWindow::changeLocation); // 向工具欄新增動作和部件 ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Back)); ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Forward)); ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Reload)); ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Stop)); ui->mainToolBar->addWidget(locationEdit); } MainWindow::~MainWindow() { delete ui; } // 位址列按下回車處理槽 void MainWindow::changeLocation() { QUrl url = QUrl(locationEdit->text()); view->load(url); view->setFocus(); } void MainWindow::setProgress(int p) { progress = p; adjustTitle(); } // 調整標題槽 void MainWindow::adjustTitle() { if ( progress <= 0 || progress >= 100) { setWindowTitle(view->title()); } else { setWindowTitle(QString("%1 (%2%)").arg(view->title()).arg(progress)); } } // 載入完成處理槽 void MainWindow::finishLoading(bool finished) { if (finished) { progress = 100; setWindowTitle(view->title()); } else { setWindowTitle("web page loading error!"); } }
view=newQWebEngineView(this);
view->load(QUrl("http://localhost/wangye/index.php"));
setCentralWidget(view);
resize(1024,680);
這段程式碼是新建一個QWebEngineView類物件,並把url賦值,也就是相當於在瀏覽器的域名中輸入了網頁url
ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Back));ui->mainToolBar->addAction(view->pageAction(
ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Stop));
ui->mainToolBar->addWidget(locationEdit);
這段程式碼是通過QWebEngineView類寫好的方法來記錄網頁的history,實現網頁的Back,Forward,Reload和Stop,並且繫結訊號與槽實現在瀏覽器的url輸入欄中輸入地址會讀取url的text,實現新頁面的跳轉
其實就是別人寫好的東西來拿用,被人寫後了web engine這個類,給你個介面,你會用就行