一、需求:
对于Qt 通过QWebEngineView 实现快捷键F12打开Web调试窗口。
二、方法:
方法一:QWebEngineView ::addAction(QAction); QAction::setShortcut(QKeySequence)
方法二:1、new QShortcut 2、QObject::connect(shortcut, &QShortcut::activated ....
方法三:1、new QMenu 2、new QAction 3、QMenu::addAction() 4、new QMenuBar 5、 QMenuBar::addMenu() 6、 QMainWindow::setMenuBar(QMenuBar *)
三、代码:
#include <QtWidgets/QApplication>
#include <QWebEngineView>
#include <QWebEnginePage>
#include <QShortcut>
#include <QObject>
#include <QKeySequence>
#include <QAction>
QWebEngineView* setPageInspectElementShortCut(QWebEngineView* pWebEngineView, QKeySequence &keySequent,const QString qstrActionName = QString() ) {
if (!pWebEngineView || keySequent.isEmpty())
{
return nullptr;
}
QAction *pAction = new QAction(qstrActionName, pWebEngineView);
pAction->setShortcut(keySequent);
QWebEngineView *m_pNewView;
QObject::connect(pAction, &QAction::triggered, [pWebEngineView, m_pNewView]()mutable {
m_pNewView = new QWebEngineView();
pWebEngineView->page()->setDevToolsPage(m_pNewView->page());
pWebEngineView->page()->triggerAction(QWebEnginePage::InspectElement);
m_pNewView->show();
});
pWebEngineView->addAction(pAction);
return m_pNewView;
}
QWebEngineView* setPageInspectElementShortCut2(QWebEngineView* pWebEngineView, QKeySequence &keySequent) {
if (!pWebEngineView || keySequent.isEmpty())
{
return nullptr;
}
QShortcut* shortcut = new QShortcut((keySequent), pWebEngineView);
//int nShortcutId = shortcut->id();
//m_pWebView->setShortcutEnabled(nShortcutId,true); 不用添加也可以
QWebEngineView *m_pNewView;
QObject::connect(shortcut, &QShortcut::activated, pWebEngineView, [pWebEngineView, m_pNewView]()mutable {
m_pNewView = new QWebEngineView();
pWebEngineView->page()->setDevToolsPage(m_pNewView->page());
pWebEngineView->page()->triggerAction(QWebEnginePage::InspectElement);
m_pNewView->show();
});
return m_pNewView;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWebEngineView *m_pWebView = new QWebEngineView();
m_pWebView->setUrl(QStringLiteral("https://www.baidu.com"));
m_pWebView->show();
// 方法一:pWebEngineView->addAction(pAction);
// QWebEngineView *pInsEleView = setPageInspectElementShortCut(m_pWebView, QKeySequence(Qt::Key_F12));
//对调试的那个窗口的view在自行处理。
// 方法二: 1、new QShortcut 2、QObject::connect(shortcut, &QShortcut::activated ....
QWebEngineView *pInsEleView = setPageInspectElementShortCut2(m_pWebView, QKeySequence(Qt::Key_F12));
return a.exec();
}