一、QWebEngineView网页跳转
webwindow.h
class WebWindow:public QWebEngineView
{
Q_OBJECT
public:
explicit WebWindow(QWidget*parent=nullptr);
protected:
QWebEngineView*createWindow(QWebEnginePage::WebWindowType);//左键打开网页
};
webwindow.cpp
WebWindow::WebWindow(QWidget*parent):QWebEngineView(parent){}
QWebEngineView*WebWindow::createWindow(QWebEnginePage::WebWindowType)
{
return this;
}//给方法为enumQWebEnginePage::WebWindowType
mainwindow.cpp//没有UI文件的情况下,而且在mainwindow.h已经声明webbrowser
MainWindow::MainWindow(QWidget *parent)
:QMainWindow(parent)
{
webbrowser=new WebWindow(this);
webbrowser->load(QUrl("https://www.so.com/"));
}
MainWindow::~MainWindow(){}
二、QWebEngineView基本浏览功能
webwindow.h
加入
public:
QUrl now_url;
public slots:
void linkHovered(const QString &url);
webwindow.cpp
往WebWindow::WebWindow(QWidget *parent) :QWebEngineView(parent)中添加
connect(this->page(),&QWebEnginePage::linkHovered,this,&WebWindow::linkHovered);
修改createWindow(QWebEnginePage::WebWindowType)函数的内容
QWebEngineView*WebWindow::createWindow(QWebEnginePage::WebWindowType)
{
this->load(now_url);
return 0;
}
void WebWindow::linkHovered(const QString &url)
{
now_url=url;
}
mainwindow.cpp
添加按钮,点击按钮实现以下功能
前进:webbrowser->forward();
后退:webbrowser->back();
刷新:webbrowser->reload();
三、QWebEngineView下载功能
webwindow.h
在其中添加
signals:
void downloadRequested(QWebEngineDownloadItem *softdownload);
void dataChanged(qint64,qint64);
public slots:
void downloadJump(QWebEngineDownloadItem *softdownload);
void setCurrentProgress(qint64 bytesreceived,qint64 bytestotal);
webwindow.cpp
往WebWindow::WebWindow(QWidget *parent) :QWebEngineView(parent)中添加
connect(this->page()->profile(),&QWebEngineProfile::downloadRequested,this,&WebWindow::downloadJump);
在cpp中添加void WebWindow::downloadJump(QWebEngineDownloadItem*softdownload)
{
softdownload->accept();
connect(softdownload,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(setCurrentProgress(qint64,qint64)));
}
void WebWindow::setCurrentProgress(qint64 bytesreceived,qint64 bytestotal)
{
emit dataChanged(bytesreceived,bytestotal);
}
mainwindow.cpp//已经声明进度条控件为progressBar
在MainWindow::MainWindow(QWidget *parent): QMainWindow(parent)中新建进度条控件为progressBar,再其中添加
connect(webbrowser,SIGNAL(dataChanged(qint64,qint64)),this,SLOT(append(qint64,qint64)));//WebEngineView传递参数给MainWindow
在cpp添加
void MainWindow::append(qint64 bytesreceived,qint64 bytestotal)
{
progressBar->setValue(bytesreceived);
progressBar->setMaximum(bytestotal);
if(bytesreceived==bytestotal){
progressBar->hide();
qDebug()<<QString("下载完成");
}
if(bytesreceived!=bytestotal){
progressBar->show();
qDebug()<<QString("正在下载");
}
}