Skip to content

Instantly share code, notes, and snippets.

@hasselmm
Last active June 7, 2021 14:24
Show Gist options
  • Save hasselmm/8eff9a5db89b8754b3363d92d7c10502 to your computer and use it in GitHub Desktop.
Save hasselmm/8eff9a5db89b8754b3363d92d7c10502 to your computer and use it in GitHub Desktop.
Function binding for QML
// Basic idea is to export the function as a Qt property that holds a JavaScript callable
Q_PROPERTY(QJSValue hasRoles READ hasRolesFunction NOTIFY rolesChanged FINAL)
// Possible implementation of such property
QJSValue ProfileService::hasRolesFunction()
{
// create function factory to bind `this`
auto factory = qmlEngine(this)->evaluate("profileService => (roles => (profileService.roles & roles) === roles)"_l1);
if (factory.isError()) {
qCCritical(lcProfile, "Could not create hasRoles() factory: %ls", qUtf16Printable(factory.toString()));
return {};
}
// create actual function bound to `this`
auto function = factory.call({qml->newQObject(this)});
if (function.isError()) {
qCCritical(lcProfile, "Could not create hasRoles() function: %ls", qUtf16Printable(function.toString()));
return {};
}
return function;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment