简体   繁体   中英

How to display a QWebEngineView in Qt mainwindow?

My webview function with the following code in my main.cpp :

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);

   QWebEngineView view;
   view.setUrl(QUrl(QStringLiteral("http://qt-project.org/")));
   view.show();
   return app.exec();
}

However, I want to have a MainWindow view and embed my web view in a specific widget inside my mainwindow.cpp . Here is the code that doesn't work and I'm a bit mixed up with the parent attribut and the object to put in my mainwindow.ui (design tool).

QWebEngineView *view = new QWebEngineView(parent);
ui->webView->load(QUrl("http://qt-project.org/"));
view->show();

Here is the code for a similar widget that displayed correctly in my project:

QMovie *load = new QMovie(":/animations/scanner.gif");
ui->movieView->setMovie(load);
load->start();

You would either use your view as the central widget or put it into a layout if you need more than just a central widget directly in your mainwindow.

Central Widget

#include <QApplication>
#include <QMainWindow>

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   QMainWindow mainWindow;
   QWebEngineView view;
   view.setUrl(QUrl(QStringLiteral("http://qt-project.org/")));
   mainWindow.setCentralWidget(view);
   mainWindow.show();
   return app.exec();
}

Layout

#include <QApplication>
#include <QMainWindow>

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   QMainWindow mainWindow;
   QWebEngineView view;
   view.setUrl(QUrl(QStringLiteral("http://qt-project.org/")));
   mainWindow.layout()->addWidget(view);
   mainWindow.show();
   return app.exec();
}

These are just examples with standard QMainWindows, as we do not have access to your mainwindow.cpp, and it should not matter much either. You can apply these concepts in your mainwindow.cpp just as well.

Similarly, you can also have layouts inside other children, grandchildren, etc, widgets of your mainwindow instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM