Skip to content

Instantly share code, notes, and snippets.

@Tosainu
Last active November 21, 2021 23:54
Show Gist options
  • Save Tosainu/3e14b290d4703a52e574 to your computer and use it in GitHub Desktop.
Save Tosainu/3e14b290d4703a52e574 to your computer and use it in GitHub Desktop.
QWebViewの中の<button>からC++のコードを呼び出すテスト
#ifndef JSOBJ_H
#define JSOBJ_H
#include <QtCore>
#include <QDebug>
class JsObj : public QObject {
Q_OBJECT
public:
JsObj(QObject *parent = nullptr) : QObject(parent) {}
public slots:
void myon() {
qDebug() << "myon!!";
}
};
#endif
#include <QApplication>
#include "mainwindow.h"
auto main(int argc, char **argv) -> int {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
#include "mainwindow.h"
#include "jsobject.h"
MainWindow::MainWindow() {
auto webview = new QWebView(this);
webview->setHtml(R"(
<html lang="en">
<head>
<meta charset="UTF-8">
<title>にゃーん</title>
</head>
<body>
<h1>にゃーん</h1>
<p>This is test page.</p>
<button onclick="jsobj.myon();">Click me</button>
</body>
</html>
)");
webview->page()->mainFrame()->addToJavaScriptWindowObject("jsobj", new JsObj());
this->setCentralWidget(webview);
}
MainWindow::~MainWindow() {}
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtWebKitWidgets>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow();
~MainWindow();
};
#endif
QT += core gui webkitwidgets
TEMPLATE = app
TARGET = webframe_test
INCLUDEPATH += .
HEADERS += mainwindow.h jsobject.h
SOURCES += main.cc mainwindow.cc
CONFIG += c++11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment