web页面自适应QWebEngineView的大小

#ifndef OPENVIPDIALOG_H
#define OPENVIPDIALOG_H
#include 
#include "draggabledialog.h"
#include 
namespace Ui {
class OpenVipDialog;
}
class OpenVipDialog : public DraggableDialog
{
    Q_OBJECT

public:
    explicit OpenVipDialog(QWidget *parent = nullptr);
    ~OpenVipDialog();
private slots:
    void on_close_btn_clicked();
private:
    Ui::OpenVipDialog *ui;
    QWebEngineView *webEngineView;  // 添加这一行
};
#endif // OPENVIPDIALOG_H
#include "openvipdialog.h"
#include "ui_openvipdialog.h"
OpenVipDialog::OpenVipDialog(QWidget *parent) :
    DraggableDialog(parent),
    ui(new Ui::OpenVipDialog)
{
    ui->setupUi(this);

    // 配置 QWebEngineView
    // 初始化webEngineView
    webEngineView = new QWebEngineView(ui->frame);
    webEngineView->setGeometry(0, 73, 1139, 763); // 设置大小和位置
    webEngineView->load(QUrl("http://www.baidu.com"));
    // 当页面加载完成时执行此操作
    connect(webEngineView->page(), &QWebEnginePage::loadFinished, [this](bool ok) {
        if (ok) {
            // 1. 获取页面内容的宽度
            webEngineView->page()->runJavaScript("document.body.scrollWidth", [this](const QVariant &widthResult) {
                int pageWidth = widthResult.toInt();
                int viewWidth = webEngineView->width();
                double zoomFactorWidth = static_cast(viewWidth) / static_cast(pageWidth);

                // 2. 获取页面内容的高度
                webEngineView->page()->runJavaScript("document.body.scrollHeight", [this, zoomFactorWidth](const QVariant &heightResult) {
                    int pageHeight = heightResult.toInt();
                    int viewHeight = this->webEngineView->height();
                    double zoomFactorHeight = static_cast(viewHeight) / static_cast(pageHeight);
                    // 3. 根据宽度和高度计算缩放因子,并设置
                    double zoomFactor = qMin(zoomFactorWidth, zoomFactorHeight); // 取两者中较小的一个,以确保完全适合
                    webEngineView->setZoomFactor(zoomFactor);
                });
            });
        }
    });

}

你可能感兴趣的:(前端)