Qt WebChannel JavaScript API
JavaScript API 설정
QWebChannel 또는 WebChannel 과 통신하려면 클라이언트는 qwebchannel.js 에서 제공하는 JavaScript API를 사용하고 설정해야 합니다. Qt WebEngine내부에서 실행되는 클라이언트의 경우, 페이지를 로컬에서 로드하는 경우 qrc:///qtwebchannel/qwebchannel.js 을 통해 파일을 불러올 수 있으며, 그렇지 않은 경우 QWebEngineUrlScheme 에 QWebEngineUrlScheme::SecureScheme 으로 등록된 QWebEngineUrlSchemeHandler 에서 qwebchannel.js 에 접근할 수 있도록 설정해야 합니다. 외부 클라이언트의 경우, 파일을 웹 서버에 복사해야 합니다. 그런 다음 QWebChannel 객체를 인스턴스화하고, 이 객체에 전송(transport) 객체와 콜백 함수를 전달합니다. 이 콜백 함수는 채널 초기화가 완료되고 게시된 객체를 사용할 수 있게 되면 호출됩니다. 선택적인 세 번째 인자에는 변환기 래퍼 함수의 배열 또는 단일 함수가 포함됩니다.
트랜스포트 객체는 최소한의 메시지 전달 인터페이스를 구현합니다. 이 객체는 JSON 메시지를 문자열로 변환하여 서버 측의 QWebChannelAbstractTransport 객체로 전송하는 send() 함수를 가져야 합니다. 또한, 서버로부터 메시지가 수신되면 해당 객체의 onmessage 속성이 호출되어야 합니다. 또는 WebSocket을 사용하여 인터페이스를 구현할 수도 있습니다.
JavaScript의 QWebChannel 객체는 전송 객체가 완전히 작동할 수 있게 된 후에 생성해야 합니다. WebSocket의 경우, 소켓의 onopen 핸들러 내에서 QWebChannel 를 생성해야 함을 의미합니다. 구체적인 구현 방법은 Qt WebChannel 독립형 예제를 참고하십시오.
참고: 동일한 페이지 내에서 전송(transport)당 하나의 QWebChannel 객체만 생성할 수 있습니다.
변환기 래퍼 함수는 내장 변환기의 이름을 가진 문자열이거나, 처리할 객체를 인수로 받아 결과 유형을 반환하거나(해당 함수가 적용되지 않을 경우 undefined를 반환)하는 사용자 정의 함수입니다. undefined가 반환되면 다음 변환기가 처리됩니다. undefined 이외의 값을 반환하는 변환기가 없는 경우, 처리는 정상적으로 진행됩니다. 현재 유일한 내장 변환기 함수는 “Date”입니다. 이 함수는 ISO 8601 형식의 날짜가 포함된 문자열을 인수로 받아, 구문이 올바르고 날짜가 유효할 경우 새로운 Date 객체를 반환합니다.
QObject와의 상호 작용
QWebChannel 객체에 전달된 콜백이 호출되면 채널의 초기화가 완료되며, HTML 클라이언트는 channel.objects 속성을 통해 게시된 모든 객체에 접근할 수 있습니다. 따라서 식별자 "foo"로 객체가 게시되었다고 가정할 때, 아래 예제와 같이 해당 객체와 상호작용할 수 있습니다. HTML 클라이언트와 QML/C++ 서버 간의 모든 통신은 비동기식으로 이루어진다는 점에 유의하십시오. 속성은 HTML 측에서 캐시됩니다. 또한 JSON으로 변환 가능한 QML/C++ 데이터 유형만 올바르게 (역)직렬화되어 HTML 클라이언트에서 접근할 수 있다는 점을 명심하십시오.
new QWebChannel(yourTransport, function(channel) {
// Connect to a signal:
channel.objects.foo.mySignal.connect(function() {
// This callback will be invoked whenever the signal is emitted on the C++/QML side.
console.log(arguments);
});
// To make the object known globally, assign it to the window object, i.e.:
window.foo = channel.objects.foo;
// Invoke a method:
foo.myMethod(arg1, arg2, function(returnValue) {
// This callback will be invoked when myMethod has a return value. Keep in mind that
// the communication is asynchronous, hence the need for this callback.
console.log(returnValue);
});
// Read a property value, which is cached on the client side:
console.log(foo.myProperty);
// Writing a property will instantly update the client side cache.
// The remote end will be notified about the change asynchronously
foo.myProperty = "Hello World!";
// To get notified about remote property changes,
// simply connect to the corresponding notify signal:
foo.myPropertyChanged.connect(function() {
console.log(foo.myProperty);
});
// One can also access enums that are marked with Q_ENUM:
console.log(foo.MyEnum.MyEnumerator);
});오버로드된 메서드 및 시그널
오버로드된 메서드를 가진 ` QObject `를 퍼블리시할 경우, ` QWebChannel `는 메서드 호출을 가장 잘 일치하는 것으로 해결합니다. 자바스크립트의 타입 시스템으로 인해 C++의 ‘double’과 가장 잘 매핑되는 ‘number’ 타입은 단 하나뿐이라는 점에 유의하십시오. 오버로드된 메서드들이 숫자형 매개변수의 타입만 다를 경우, QWebChannel 은 항상 자바스크립트 ‘number’ 타입과 가장 잘 일치하는 오버로드를 선택합니다. 오버로드된 시그널에 연결할 때, QWebChannel 클라이언트는 기본적으로 해당 이름의 첫 번째 시그널 오버로드에만 연결합니다. 또한, 메서드와 시그널의 오버로드는 완전한 QMetaMethod 시그니처를 사용하여 명시적으로 요청할 수 있습니다. C++ 측에 다음과 같은 ` QObject ` 서브클래스가 있다고 가정해 보겠습니다:
class Foo : public QObject
{
Q_OBJECT
slots:
void foo(int i);
void foo(double d);
void foo(const QString &str);
void foo(const QString &str, int i);
signals:
void bar(int i);
void bar(const QString &str);
void bar(const QString &str, int i);
};이 경우 JavaScript 측에서 다음과 같이 이 클래스와 상호 작용할 수 있습니다:
// methods
foo.foo(42); // will call the method named foo which best matches the JavaScript number parameter, i.e. foo(double d)
foo.foo("asdf"); // will call foo(const QString &str)
foo.foo("asdf", 42); // will call foo(const QString &str, int i)
foo["foo(int)"](42); // explicitly call foo(int i), *not* foo(double d)
foo["foo(QString)"]("asdf"); // explicitly call foo(const QString &str)
foo["foo(QString,int)"]("asdf", 42); // explicitly call foo(const QString &str, int i)
// signals
foo.bar.connect(...); // connect to first signal named bar, i.e. bar(int i)
foo["bar(int)"].connect(...); // connect explicitly to bar(int i)
foo["bar(QString)"].connect(...); // connect explicitly to bar(const QString &str)
foo["bar(QString,int)"].connect(...); // connect explicitly to bar(const QString &str, int i)© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.