Solved QWebEngineView How to open new tab link in same tab?
-
Hello,
I'm creating really simple browser.//main.cpp #include <QApplication> #include "mysimplebrowser.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MySimpleBrowser browser; browser.run(); return a.exec(); }
//mysimplebrowser.h #ifndef MYSIMPLEBROWSER_H #define MYSIMPLEBROWSER_H #include <QObject> #include <QWebEngineView> class MySimpleBrowser : QWebEngineView { Q_OBJECT public: void run(); }; #endif // MYSIMPLEBROWSER_H
//mysimplebrowser.cpp #include "mysimplebrowser.h" void MySimpleBrowser::run() { load(QUrl("https://qt.io")); show(); }
It works fine but there is one problem. Links that should be opened in a new tab (because of
_blank
attribute) are not working. I don't want to have tabs in my browser, I want them to open in current window. How to do that?
I tried:QWebEngineView * MySimpleBrowser::createWindow(QWebEnginePage::WebWindowType type) { return this; }
It causes crash of whole program.
Then I tried:QWebEngineView * MySimpleBrowser::createWindow(QWebEnginePage::WebWindowType type) { QWebEnginePage * newPage = new QWebEnginePage(); setPage(newPage); return this; }
It opens the link in the current window but
newPage
doesn't have history of original page, so Back button doesn't work.
S I tried this:QWebEngineView * MySimpleBrowser::createWindow(QWebEnginePage::WebWindowType type) { QWebEnginePage * oldPage = page(); QWebEnginePage * newPage = new QWebEnginePage(); QDataStream stream; stream << *(oldPage->history()); stream >> *(newPage->history()); newPage->history()->goToItem(newPage->history()->itemAt(oldPage->history()->currentItemIndex())); setPage(newPage); return this; }
But the Back button still doesn't work and I'm out of ideas.
-
A long time ago I solved a similar problem in SO (see this answer for more information) and the logic was to create a new QWebEnginePage, get the url, set it to the original QWebEnginePage and delete the new QWebEnginePage.
#include <QtWebEngineWidgets> class WebEnginePage: public QWebEnginePage{ Q_OBJECT public: using QWebEnginePage::QWebEnginePage; protected: QWebEnginePage *createWindow(WebWindowType ){ WebEnginePage *page = new WebEnginePage(this); connect(page, &QWebEnginePage::urlChanged, this, &WebEnginePage::onUrlChanged); return page; } private Q_SLOTS: void onUrlChanged(const QUrl & url){ if(WebEnginePage *page = qobject_cast<WebEnginePage *>(sender())){ setUrl(url); page->deleteLater(); } } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QWebEngineView view; view.setPage(new WebEnginePage(&view)); view.load(QUrl(QStringLiteral("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_a_target"))); view.resize(640, 480); view.show(); return a.exec(); } #include "main.moc"