Qt WebChannel JavaScript API
JavaScript API 설정하기
QWebChannel 또는 WebChannel 와 통신하려면 클라이언트는 qwebchannel.js
에서 제공하는 JavaScript API 를 사용하고 설정해야 합니다. 내부에서 실행되는 클라이언트의 경우 Qt WebEngineqrc:///qtwebchannel/qwebchannel.js
를 통해 파일을 로드할 수 있습니다. 외부 클라이언트의 경우 파일을 웹 서버에 복사해야 합니다. 그런 다음 QWebChannel 객체를 인스턴스화하고 전송 객체와 콜백 함수를 전달하면 채널의 초기화가 완료되고 게시된 객체를 사용할 수 있게 되면 호출됩니다. 선택적 세 번째 인수는 변환기 래퍼 함수 배열 또는 단일 함수를 포함합니다.
전송 객체는 최소한의 메시지 전달 인터페이스를 구현합니다. 이 객체는 문자열화된 JSON 메시지를 받아 서버 측 QWebChannelAbstractTransport 객체로 전송하는 send()
함수가 있는 객체여야 합니다. 또한 서버에서 메시지를 수신하면 onmessage
프로퍼티가 호출되어야 합니다. 또는 웹소켓을 사용하여 인터페이스를 구현할 수도 있습니다.
전송 객체가 완전히 작동하면 자바스크립트 QWebChannel 객체를 생성해야 한다는 점에 유의하세요. 웹소켓의 경우 소켓의 onopen
핸들러에 QWebChannel 을 생성해야 한다는 뜻입니다. Qt WebChannel 독립형 예제에서 이 작업을 수행하는 방법을 살펴보세요.
참고: 전송당 하나의 QWebChannel
객체만 같은 페이지에 만들 수 있습니다.
변환기 래퍼 함수는 내장된 변환기 이름이 포함된 문자열이거나 처리할 객체를 인수로 받아 결과 유형을 반환하는 사용자 제공 함수이거나 함수가 적용되지 않는 경우 미정의입니다. 미정의가 반환되면 다음 변환기가 처리됩니다. 정의되지 않음 이외의 값을 반환하는 변환기가 없는 경우 처리는 정상적으로 진행됩니다. "날짜"는 현재 유일하게 내장된 변환기 함수입니다. 이 함수는 ISO 8601 날짜가 포함된 문자열을 받아 구문이 맞고 날짜가 유효한 경우 새 Date 객체를 반환합니다.
QObject와 상호 작용하기
QWebChannel 개체에 전달된 콜백이 호출되면 채널의 초기화가 완료되고 모든 게시된 개체는 channel.objects
속성을 통해 HTML 클라이언트에서 액세스할 수 있습니다. 따라서 식별자가 "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'에 가장 잘 매핑되는 '숫자' 타입은 단 하나뿐이라는 점에 유의하세요. 오버로드가 숫자와 유사한 매개변수의 유형만 다를 경우 QWebChannel 은 항상 JavaScript '숫자' 유형과 가장 잘 일치하는 오버로드를 선택합니다. 오버로드된 신호에 연결하면 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); };
그러면 자바스크립트 측에서 이 클래스와 다음과 같이 상호작용할 수 있습니다:
// 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)
© 2025 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.