QWebEngine的坑与Qt窗口切换导致的闪烁

本文档详细介绍了QWebEngine视图组件在使用过程中遇到的常见问题及其解决办法,包括避免崩溃、消除闪屏现象、解决HTTPS访问及录音问题。通过正确的析构、设置OpenGL属性、使用自定义QWebEnginePage类等方法,有效提升应用稳定性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

QWebEngine的坑

1.崩溃

原因是没有delete析构。解决方法:

    delete m_webEngineView;
    m_webEngineView= nullptr;

2.闪屏

在窗口设置了下面这个属性后就会在切换窗口的时候闪屏。

setWindowFlags(Qt::FramelessWindowHint);	//去掉边框

解决方法:

    //在QApplication构造前调用,解决QWebEngine导致的闪屏问题
    QCoreApplication::setAttribute(Qt::AA_UseSoftwareOpenGL);
	QApplication a(argc, argv);

Qt窗口切换导致的闪烁

解决方法:在A窗口show之后延时关闭或隐藏B窗口。

    aWindow->show();

    //延迟关闭主窗口
    QTimer::singleShot(10, [this]() {
        hide();
    });

解决HTTPS网站无法访问的问题,解决无法录音的问题:

主要是继承QWebEnginePage,重新实现相关函数。

CustomWebEnginePage.h

#ifndef CUSTOMWEBENGINEPAGE_H
#define CUSTOMWEBENGINEPAGE_H

#include <QWebEnginePage>

class CustomWebEnginePage : public QWebEnginePage
{
	Q_OBJECT

public:
	CustomWebEnginePage(QObject *parent = Q_NULLPTR);

	// 关闭HTTPS验证
	virtual bool certificateError(const QWebEngineCertificateError &certificateError);

private Q_SLOTS:
	// 获取音频和视频捕获的权限,解决不能录音的bug
	void onFeaturePermissionRequested(const QUrl &securityOrigin, QWebEnginePage::Feature feature);

};

#endif // CUSTOMWEBENGINEPAGE_H

CustomWebEnginePage.cpp

#include "customwebenginepage.h"

CustomWebEnginePage::CustomWebEnginePage(QObject *parent/* = Q_NULLPTR*/)
	: QWebEnginePage(parent)
{
	connect(this, &CustomWebEnginePage::featurePermissionRequested, this, &CustomWebEnginePage::onFeaturePermissionRequested);
}

bool CustomWebEnginePage::certificateError(const QWebEngineCertificateError &certificateError)
{
	return true;
}

void CustomWebEnginePage::onFeaturePermissionRequested(const QUrl &securityOrigin, QWebEnginePage::Feature feature)
{
	if (feature == QWebEnginePage::MediaAudioCapture
		|| feature == QWebEnginePage::MediaVideoCapture
		|| feature == QWebEnginePage::MediaAudioVideoCapture)
		setFeaturePermission(securityOrigin, feature, QWebEnginePage::PermissionGrantedByUser);
	else
		setFeaturePermission(securityOrigin, feature, QWebEnginePage::PermissionDeniedByUser);
}

 MainWindow.cpp

    m_webView = new QWebEngineView();
	m_webView->setPage(new CustomWebEnginePage());
    m_webView->setFixedSize(QApplication::desktop()->availableGeometry().width(), QApplication::desktop()->availableGeometry().height()-40);

	QString url = CONFIG.serverUrl();
	//m_webView->load(QString("https://www.baidu.com"));
	m_webView->load(url);
    m_webView->show();

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值