【发布时间】:2017-02-26 01:09:50
【问题描述】:
我正在尝试使用 QWebEngineView 创建一个窗口,并在窗口关闭后删除 QWebEngineView。但是,QWebEngineView 似乎永远不会被删除,并且会继续运行我加载的任何 QUrl(例如 YouTube 视频)。在我的程序中,我有一个带有 Line Edit 和 Push Button 的 QMainWindow,它创建了一个加载用户输入的 URL 的窗口。这是我的代码:
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "subwindow.h"
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
void init();
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
SubWindow *sub;
};
#endif // MAINWINDOW_H
子窗口.h
#ifndef SUBWINDOW_H
#define SUBWINDOW_H
#include <QMainWindow>
#include <QtWebEngineWidgets/qwebengineview.h>
#include <QTimer>
namespace Ui
{
class SubWindow;
}
class SubWindow : public QMainWindow
{
Q_OBJECT
public:
explicit SubWindow(QWidget *parent = 0);
void doWeb(QString link);
~SubWindow();
private:
Ui::SubWindow *ui;
QWebEngineView *web;
private slots:
void on_pushButton_clicked();
};
#endif // SUBWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
void MainWindow::init()
{
this->showMaximized();
sub = new SubWindow(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
sub->doWeb(ui->lineEdit->text());
}
SubWindow.cpp
#include "subwindow.h"
#include "ui_subwindow.h"
SubWindow::SubWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SubWindow)
{
ui->setupUi(this);
}
void SubWindow::doWeb(QString link)
{
this->show();
web = new QWebEngineView(this);
ui->verticalLayout->addWidget(web);
web->load(QUrl(link, QUrl::TolerantMode));
web->show();
}
SubWindow::~SubWindow()
{
delete web; //Doesn't seem to work, since memory is still allocated in task manager
delete ui;
}
void SubWindow::on_pushButton_clicked()
{
this->close(); //Artifact for testing purposes.
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.init();
return a.exec();
}
我也尝试过使用“web->close();” (我把它放在我有测试工件的地方)与
“web->setAttribute(Qt::WA_DeleteOnClose);” (我把它放在“web = new QWebEngineView(this);”之后),但这也没有解决我的问题。有谁知道我做错了什么?
【问题讨论】:
-
你怎么知道QWebEngine没有被销毁?
-
首先,我使用任务管理器,注意到在我按下 MainWindow Push Button 之前,程序使用了大约 55MB 的 RAM。在我按下它之后,它变成了大约 144MB,在关闭子窗口后仍然保持分配。除此之外,当我加载 YouTube 视频时,我仍然可以听到关闭窗口后播放的声音。